write to json file in javascript

You can use the fs (file system) module in Node.js to write to a JSON file asynchronously. Here's an example:

const fs = require('fs');

const data = { name: 'John Doe', age: 35 };

const writeFile = (filename, content) => {
  return new Promise((resolve, reject) => {
    fs.writeFile(filename, content, err => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
};

writeFile('data.json', JSON.stringify(data))
  .then(() => console.log('Successfully wrote to file'))
  .catch(err => console.error('Error writing to file:', err));
467 chars
20 lines

In this example, we first define an object data that we want to write to a JSON file. We then define a function writeFile that takes a filename and content, and returns a promise that resolves if the file was successfully written, or rejects if there was an error.

We use the JSON.stringify method to convert the data object to a JSON string before writing it to the file.

Finally, we call writeFile with the filename 'data.json' and the JSON stringified data object, and handle any errors or successful writes with the Promises returned by writeFile.

gistlibby LogSnag