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



我正在循环浏览文件夹中包含的所有图像,对于每个图像,我需要将其路径、日期(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!`);
}
);
});

最新更新