使用 node js / javascript 读取所有文件并存储在一个文件中

read all the files and store in one file using node js / javascript

我的 project/Folder

中有 3 个 Json 文件

file1.json

{
  "id":"01",
  "name":"abc",
  "subject":[
    "subject1":"Maths",
    "subject2":"Science"
  ]
}

File2.json

{
  "id":"01",
  "name":"dummy",
  "Degree":[
    "Graduation":"BCom",
    "Post Graduation":"MBA"
  ]
}

File3.json

{
  "id":"BA01",
  "Address":"India",
  "P Address":[
    "State":"MP",
    "City":"Satna"
  ]
}

我写了一个代码,可以读取我的 project/Folder 这样我就可以读取里面的所有数据json 文件并想附加到我的 output.json

fs.readdir(
    path.join(process.cwd(), "project/Folder"),
    (err, fileNames) => {
      if (err) throw console.log(err.message);
      // Loop fileNames array
      fileNames.forEach((filename) => {
        // Read file content
        fs.readFile(
          path.join(
            process.cwd(),
            "project/Folder",
            `${filename}`
          ),
          (err, data) => {
            if (err) throw console.log(err.message);
            // Log file content
            const output = JSON.parse(data);
            fs.appendFile(
              path.join(
                process.cwd(),
                "project/Folder",
                `output.json`
              ),
              `[${JSON.stringify(output)},]`,
              (err) => {
                if (err) throw console.log(err.message);
              }
            );
          }
        );
      });
    }
  );

我的预期输出是这样的,因为我想将我从 file1、file2、file3 json 获得的数据附加到 output.json

[
   {
      file1.json data
   },
   {
      file2.json data
   },
   {
      file3.json data
   }
]

但实际上我将其作为输出

[
  {
    file1.josn data
  },
]
[
  {
    file2.josn data
  },
]
[
  {
    file3.josn data
  },
]

即使我正确地编写了代码,我也不知道如何才能像这样实现预期的输出,但我想我遗漏了一些东西,但我不知道有人可以帮助我实现预期的代码吗?

[
   {
      file1.json data
   },
   {
      file2.json data
   },
   {
      file3.json data
   }
]

老实说,我并不完全理解。但是这一行(fs.appendFile 的第二个参数):

`[${JSON.stringify(output)},]`,

如果你把它改成

`${JSON.stringify(output)},`,

将使结果如下所示:

{
   file1.json data
},
{
   file2.json data
},
{
   file3.json data
}

然后你可以用括号[].

把它们包起来
const arr = [];

fs.readdir(path.join(process.cwd(), "project/Folder"), (err, fileNames) => {
  if (err) throw console.log(err.message);
  // Loop fileNames array
  fileNames.forEach((filename) => {
    // Read file content
    fs.readFile(
      path.join(process.cwd(), "project/Folder", `${filename}`),
      (err, data) => {
        if (err) throw console.log(err.message);
        // Log file content
        const output = JSON.parse(data);
        arr.push(output);
        fs.writeFileSync(
          path.join(process.cwd(), "project/Folder", `output.json`),
          JSON.stringify(arr),
          (err) => {
            if (err) throw console.log(err.message);
          }
        );
      }
    );
  });
});

可能是这样,push到一个数组中,然后保存到一个新文件中