Writing JSON to a File Using Node.js

To write JSON data to a file in Node.js, you can use the fs (File System) module. To do this, you must first convert the JSON data into a string using the JSON.stringify() method and then write the resulting string to a file using the fs.writeFile() method. Writing a JSON string to a file is the same as writing any other text data to a file. Alternatively, you can use a third-party library "jsonfile", specifically designed to work with JSON files in Node.js, making reading and writing JSON files in Node.js much easier. In this Node.js Write File Example, we write JSON data to a file using the JSON.stringify() and fs.writeFile() methods. Click Execute to run the Node.js Write File Example online and see the result.
Writing JSON to a File Using Node.js Execute
const fs = require('fs');

const data = {
    id: 12345,
    name: 'John Smith',
};

const jsonData = JSON.stringify(data, null, 4);

fs.writeFile('data.json', jsonData, (err) => {
    if (err) {
        console.error('Error writing file:', err);
    } else {
        console.log('Writing JSON to file was successful.');
    }
});