Appending Data to JSON File in Node.js Without Overwriting

Good points! But let’s take it a step further. What if we treat our JSON file more like a database and avoid rewriting the whole thing? We can do that by appending new entries as separate lines. Here’s how you can do it:

const fs = require('fs');

const filePath = 'myjsonfile.json';

// If file doesn’t exist, create it with an empty array
if (!fs.existsSync(filePath)) {
    fs.writeFileSync(filePath, '[]', 'utf8');
}

// Append new data without rewriting everything
fs.readFile(filePath, (err, data) => {
    let jsonArray = JSON.parse(data.toString());

    for (let i = 0; i < 5; i++) {
        jsonArray.push({ id: i, square: i * i });
    }

    fs.writeFile(filePath, JSON.stringify(jsonArray, null, 2), (err) => {
        if (err) console.error("Error writing file:", err);
    });
});

This way, instead of rewriting the entire file, we only append new objects to the existing array—making nodejs write json to file much faster, more scalable, and more reliable!