node.js fs.appendFile 附加 JSON 对象时如何添加逗号分隔符?

How to add comma separator when appending JSON objects with node.js fs.appendFile?

我正在遍历文件夹中包含的所有图像,对于每个图像,我需要将其路径、日期(null)和一个布尔值添加到一个对象中 JSON。

这是代码:

files.forEach(file => {
  fs.appendFile(
    'images.json', JSON.stringify({directory: `${sourcePathDesktopWin}/${folder}/${file}`, posted: false, date: null}, null, 2), (err) => {
      if (err) throw err;
      console.log(`The ${file} has been saved!`);
    }
  );
});

这是结果:

{
  "directory": "D:/directory1/test1.jpg",
  "posted": false,
  "date": null
}{
  "directory": "D:/directory1/test2.jpg",
  "posted": false,
  "date": null
}

正如您在附加时看到的那样,它没有在每个 JSON 对象之间添加逗号分隔符。 我该如何添加?

在您当前的示例中,如前所述,只需添加逗号即可使其无效 JSON。但是,如果将其设为数组,结果将是一个有效对象。

最简单的方法是创建一个空数组并将每个 JSON 对象推送到它。

images = [];
files.forEach(file => {
  images.push({directory: `${sourcePathDesktopWin}/${folder}/${file}`, posted: false, date: null})  
});

然后您可以将此数组写入文件。您的结果将是:

[
  {
    "directory": "D:/directory1/test1.jpg",
    "posted": false,
    "date": null
  },
  {
    "directory": "D:/directory1/test2.jpg",
    "posted": false,
    "date": null
  }
]

在我的例子中,在 JSON.stringify() 的第一个参数之后放置一个 + ',' 解决了这个问题

你的代码看起来像这样

files.forEach(file => {
  fs.appendFile(
    'images.json', JSON.stringify({directory: `${sourcePathDesktopWin}/${folder}/${file}`, posted: false, date: null}, null, 2) + ',', (err) => {
      if (err) throw err;
      console.log(`The ${file} has been saved!`);
    }
  );
});