-1

i have a function that scans a directory and builds a key,value pair of all folders and their respective files in it.

const listNotes =  () => {
    const listing = [];
    try{
      const folders = fs.readdirSync(defaultPath);
      folders.forEach((folder) => {
        let v = fs.readdirSync(`${defaultPath}/${folder}`);
        listing[folder] = v;
      });

      
    } catch (err) {
      console.log(err);
    } 
    return listing;
  };

and this is an output of such scan

[ DailyTask: [ 'Chores.json' , 'Sunday.json'] ]

that is a folder called DailyTask containing 2 files.

How do i convert this structure to JSON.

Nathaniel Babalola
  • 617
  • 2
  • 6
  • 15

1 Answers1

0

The problem with your listing variable is that it's an Array. JSON.stringify() doesn't include all the keys in the array, just the order of items, such as listing[0], listing[1]. In your case, you aren't really using listing as an array, you are using is as an object. You can just make it a object, and then when you call JSON.stringify() it will include the keys.

Solution

const listNotes =  () => {
    const listing = {};
    try{
      const folders = fs.readdirSync(defaultPath);
      folders.forEach((folder) => {
        let v = fs.readdirSync(`${defaultPath}/${folder}`);
        listing[folder] = v;
      });

      
    } catch (err) {
      console.log(err);
    } 
    return listing;

    //If you want to convert to JSON
    console.log(JSON.stringify(listing));
  };
programmerRaj
  • 1,810
  • 2
  • 9
  • 19