【问题标题】:read all the files and store in one file using node js / javascript使用节点 js / javascript 读取所有文件并存储在一个文件中
【发布时间】:2022-01-31 01:56:10
【问题描述】:

我的项目/文件夹

中有 3 个 Json 文件

file1.json

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

文件2.json

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

文件3.json

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

我写了一个代码,我可以在其中读取我的 项目/文件夹,这样我就可以读取 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);
              }
            );
          }
        );
      });
    }
  );

我的预期输出是这样的,因为我想在 output.json 中附加从 file1、file2、file3 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
   }
]

【问题讨论】:

  • 这是供您在本地机器上的个人日常使用还是应用程序的代码?如果它是为了您的特定个人用途,还有一个简单的替代方案,只需几行 bash 脚本。
  • 你不能直接追加到一个 JSON 文件而不破解文件末尾的部分解析然后选择性覆盖(不推荐)。如果要追加,请使用 CSV 格式的文件,因为它是基于行的,您可以直接将行追加到文件中。要正确添加到 JSON,您必须将其全部读入内存,将其解析到数组中,将项目添加到数组中,然后将其恢复为 JSON 并将整个文件写回磁盘。 JSON 不适合直接在磁盘上进行修改。
  • 这是一个应用程序@MImamPratama

标签: javascript node.js json nodes


【解决方案1】:
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);
          }
        );
      }
    );
  });
});

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

【讨论】:

  • 我得到的和我之前的输出一样
  • sry,现在试试,我已将代码从 fs.writeFile 更新为 fs.writeFileSync
  • 谢谢你,它现在工作完美:D
  • 不客气!也许最好将这部分 path.join(process.cwd(), "project/Folder", output.json) 更新为 ../output.json,所以它在不同的文件夹中。如果您多次运行代码,您现在拥有的方式将读取包括 output.json 在内的所有 json 文件,并尝试从所有 4 个文件写入 output.json,这样您就会得到混乱的结果
  • 我会马上做的,谢谢你的点:D
【解决方案2】:

老实说,我不明白这一切。但是这一行(fs.appendFile的第二个参数):

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

如果你改成

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

将使结果如下所示:

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

然后你可以用括号[]将它们包裹起来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 2015-02-02
    相关资源
    最近更新 更多