PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 12, 2022

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

 May 12, 2022     append, javascript, json, node.js     No comments   

Issue

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?


Solution

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
  }
]


Answered By - shubhendu madhukar
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing