简体   繁体   中英

read all the file and store in object format in node js / javascript

I wrote a code which help me to read all the folder file and make me store them in array format so my code looks like this

readAll.js

module.exports = readAllFile = () => {
  const arr = [];
  fs.readdir(path.join("./admin/requiredFiles"), (err, fileNames) => {
    if (err) throw console.log(err.message);
    // Loop fileNames array
    fileNames.forEach((filename) => {
      // Read file content
      fs.readFile(
        path.join("./admin/requiredFiles", `./${filename}`),
        (err, data) => {
          if (err) throw console.log(err.message);
          // Log file content
          arr.push(JSON.parse(data));
          fs.writeFileSync(
            path.join("./admin/execuetedFile", `config.json`),
            `${JSON.stringify(arr)}`,
            (err) => {
              if (err) throw console.log(err.message);
            }
          );
        }
      );
    });
  });
};

so this help me to read all the file which is present in admin/requiredFiles and let me save those file in executedFile

but the problem is this help me to store in array format but I want to store data in object form

suppose this is my few file data

file1.json

{
  "admin":{
    "right":"yes",
    "permission":"available"
  },
  "admin_power":{
    "addUser":"available",
    "deleteUser":"available"
  }
}

file2.json

{
  "directory":{
    "right":"yes",
    "permission":"modified"
  },
  "directory_power":{
    "add_directory":"yes",
    "assign_directory":"yes"
  }
}

so this are my some sample file and it help me to save them in format

config.json

[
 {
   "admin":{
     "right":"yes",
     "permission":"available"
   },
   "admin_power":{
     "addUser":"available",
     "deleteUser":"available"
   }
 },
 {
   "directory":{
     "right":"yes",
     "permission":"modified"
   },
   "directory_power":{
     "add_directory":"yes",
     "assign_directory":"yes"
   }
 }
]

and I don't want this in this array form I want this copied files look like this

expectation config.json

{
   "admin":{
     "right":"yes",
     "permission":"available"
   },
   "admin_power":{
     "addUser":"available",
     "deleteUser":"available"
   },
   "directory":{
     "right":"yes",
     "permission":"modified"
   },
   "directory_power":{
     "add_directory":"yes",
     "assign_directory":"yes"
   }
 }

I just wanted to know what changes should I do so I can get output in my expectation format in config,json

You can use Object.keys() instead of Array.push(). The solution is when you read each files data, you should use Object.keys method and then loop through all available keys and add it to your output object.

module.exports = readAllFile = () => {
  const output = {};
  fs.readdir(path.join("./admin/requiredFiles"), (err, fileNames) => {
    if (err) throw console.log(err.message);
    // Loop fileNames array
    fileNames.forEach((filename) => {
      // Read file content
      fs.readFile(
        path.join("./admin/requiredFiles", `./${filename}`),
        (err, data) => {
          if (err) throw console.log(err.message);
          // Log file content
          const parsedData = JSON.parse(data);
          for (let key of Object.keys(parsedData) {
           output[key] = parsedData[key];
          } 
        
          fs.writeFileSync(
            path.join("./admin/execuetedFile", `config.json`),
            `${JSON.stringify(output)}`,
            (err) => {
              if (err) throw console.log(err.message);
            }
          );
        }
      );
    });
  });
};

Use an object to collect the objects in the files, Object.assign() ( doc here ) will compound the parsed data...

// use an object (probably should rename)
let arr = {};

// rather than push, assign
Object.assign(arr, JSON.parse(data));

Again, probably better to rename arr to something like result . Remember to refer to that new variable name in the fs.writeFile .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM