nodejs append to json

To append to a JSON file in Node.js, you can use the fs module to read the existing JSON data, modify it, and then write it back to the file. Here are the steps to achieve this:

  1. First, require the fs module to be able to work with the file system:
const fs = require('fs');
  1. Read the existing JSON file using the fs.readFile method:
fs.readFile('data.json', 'utf8', (err, data) => {
  if (err) throw err;
  const jsonData = JSON.parse(data);
  // Perform the necessary modifications to the JSON data
  jsonData.newProperty = 'newValue';
  // Convert the JSON data back to a string
  const updatedData = JSON.stringify(jsonData, null, 2);
  // Write the updated data back to the file
  fs.writeFile('data.json', updatedData, (err) => {
    if (err) throw err;
    console.log('Data has been updated!');
  });
});

In this example, replace 'data.json' with the actual name of your JSON file. The modifications to the JSON data can be customized based on your specific requirements.