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

I am looping through all images contained in a folder and for each image, I need to add its path, date (null), and a boolean into an object JSON.

This is the code:

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!`);
    }
  );
});

This is the result:

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

As you can see when appending it is not adding the comma separator between each JSON object. How can I add that?


In your current example, simply adding a comma would make it an invalid JSON as pointed out already. However if you make it an array, result would be a valid object.

Simplest way to do it would be to create an empty array and push each JSON object to it.

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

You can then write this array to a file. Your result would be:

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