If you want the file to be valid JSON, you have to open your file, parse the JSON, append your new result to the array, transform it back into a string and save it again.

var fs = require('fs')

var currentSearchResult = 'example'

fs.readFile('results.json', function (err, data) {
    var json = JSON.parse(data)
    json.push('search result: ' + currentSearchResult)

    fs.writeFile("results.json", JSON.stringify(json))
})
Answer from Daniel Diekmeier on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › how-to-add-data-in-json-file-using-node-js
How to Add Data in JSON File using Node.js ? - GeeksforGeeks
July 23, 2025 - In conclusion, using Node.js's fs module, you can efficiently add data to JSON files. By reading, parsing, modifying, and writing back data, you can dynamically update your JSON files.
Discussions

How to add data to a JSON file in JavaScript?
Adding data to a JSON file in JavaScript typically involves a few steps: reading the existing data from the file, modifying the data in memory, and then writing the updated data back to the file. The specifics can vary slightly depending on the environment in which your JavaScript code is running (Node.js ... More on designgurus.io
🌐 designgurus.io
1
10
June 25, 2024
Add object to json file - Node.js
I'm trying to add an object to a very large JSON file in Node.js (but only if the id doesn't match an existing object). What I have so far: example JSON file: [ { id:123, text: "some te... More on stackoverflow.com
🌐 stackoverflow.com
October 29, 2018
How do I append to an array inside a json file in node?
If it's stored as JSON, you'd read the JSON in, parse it to JavaScript structures using JSON.parse, push the new messages to the JSON, reserialize it back to JSON, then re-write to to disk. This is quite inefficient though. It would be better to use a database. More on reddit.com
🌐 r/learnjavascript
14
4
December 26, 2022
Append to a JSON File (Node.JS, Javascript) - Stack Overflow
I currently have a json file setup with the following format: { "OnetimeCode" : "Value" } And I'd like to be able to do two things: Append to the file (change the values in the file) Add New It... More on stackoverflow.com
🌐 stackoverflow.com
April 24, 2015
Top answer
1 of 9
609

If this JSON file won't become too big over time, you should try:

  1. Create a JavaScript object with the table array in it

    var obj = {
       table: []
    };
    
  2. Add some data to it, for example:

    obj.table.push({id: 1, square:2});
    
  3. Convert it from an object to a string with JSON.stringify

    var json = JSON.stringify(obj);
    
  4. Use fs to write the file to disk

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. If you want to append it, read the JSON file and convert it back to an object

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
    }});
    

This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.

UPDATE:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.

2 of 9
57

Please try the following program. You might be expecting this output.

var fs = require('fs');

var data = {}
data.table = []
for (i=0; i <26 ; i++){
   var obj = {
       id: i,
       square: i * i
   }
   data.table.push(obj)
}
fs.writeFile ("input.json", JSON.stringify(data), function(err) {
    if (err) throw err;
    console.log('complete');
    }
);

Save this program in a javascript file, say, square.js.

Then run the program from command prompt using the command node square.js

What it does is, simply overwriting the existing file with new set of data, every time you execute the command.

Happy Coding.

🌐
HeyNode
heynode.com › tutorial › readwrite-json-files-nodejs
Read/Write JSON Files with Node.js | HeyNode
If you do know the content of the file, and can provide that detail to Node in the form of an encoding argument it generally makes the code both more performant and easier to understand. Writing JSON to the filesystem is similar to reading it. We will use fs.writeFile to asynchronously write data to a newCustomer.json file.
🌐
Evdokimovm
evdokimovm.github.io › javascript › nodejs › 2016 › 11 › 11 › write-data-to-local-json-file-using-nodejs.html
Write Data to Local JSON File using Node.js
November 11, 2016 - For append new content to users.json file we need to read the file and convert it contents to an JavaScript object using JSON.parse() method: var fs = require('fs') fs.readFile('./users.json', 'utf-8', function(err, data) { if (err) throw err var arrayOfObjects = JSON.parse(data) })
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-add-data-in-json-file-using-node-js › amp
How to Add Data in JSON File using Node.js ? | GeeksforGeeks
January 8, 2025 - Example: This example demonstrate the above approach to add data to json file using Nodejs. ... // Filename - index.js // Requiring fs module const fs = require("fs"); // Storing the JSON format data in myObject var data = fs.readFileSync("data.json"); var myObject = JSON.parse(data); // Defining new data to be added let newData = { country: "England", }; // Adding the new data to our object myObject.push(newData); // Writing to our JSON file var newData2 = JSON.stringify(myObject); fs.writeFile("data2.json", newData2, (err) => { // Error checking if (err) throw err; console.log("New data added"); });
Find elsewhere
🌐
Matheusmello
matheusmello.io › posts › javascript-write-add-data-in-json-file-using-node-js
Write / add data in JSON file using Node.js
In this updated code, we first check if the file myjsonfile.json exists. If it does, we read its content and parse it into a JavaScript object. We then loop through the data and add new elements to the table array.
🌐
npm
npmjs.com › package › jsonfile
jsonfile - npm
August 12, 2025 - const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj) .then(res => { console.log('Write complete') }) .catch(error => console.error(error))
      » npm install jsonfile
    
Published   Aug 12, 2025
Version   6.2.0
Author   JP Richardson
🌐
Educative
educative.io › answers › how-to-add-data-to-a-json-file-in-javascript
How to add data to a JSON file in JavaScript
Line 4: Read data from the file using the readFileSync() method. Lines 11–14: Modify the JavaScript object by adding new data. Line 18: Convert the JavaScript object back into a JSON string.
🌐
TutorialKart
tutorialkart.com › nodejs › node-js-write-json-object-to-file
Node.js Write JSON Object to File - Example
November 29, 2020 - nodejs-write-json-object-to-file.js · </> Copy · // file system module to perform file operations const fs = require('fs'); // json data var jsonData = '{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}'; // parse json var jsonObj = JSON.parse(jsonData); console.log(jsonObj); // stringify JSON Object var jsonContent = JSON.stringify(jsonObj); console.log(jsonContent); fs.writeFile("output.json", jsonContent, 'utf8', function (err) { if (err) { console.log("An error occured while writing JSON Object to File."); return console.log(err); } console.log("JSON file has been saved."); }); Useful Link – To access elements of JSON Object, refer Node.js Parse JSON.
🌐
Stack Abuse
stackabuse.com › reading-and-writing-json-files-with-node-js
Reading and Writing JSON Files with Node.js
July 8, 2024 - Given the extensive use of JSON ... write JSON data to a file in Node.js. In this article we'll explain how to perform these functions. Let's first see how we can read a file that has already been created. But before we do that we need to actually create the file. Open a new window in your favorite text editor and add the following ...
🌐
Reddit
reddit.com › r/learnjavascript › how do i append to an array inside a json file in node?
r/learnjavascript on Reddit: How do I append to an array inside a json file in node?
December 26, 2022 -

I’m working on a chat client and server to learn about API’s and now I need to write the messages submitted by users into the master chat log (a json file with a messages array inside of it). I have been searching for different approaches and they all error out somehow. I’m using node and express for routing if that helps.

tldr; how should one append an object to an array inside a json file using node.

edit: I’ve taken carcigenocate’s advice. I open the file, make the changes in memory, then write to the file and reload it to reflect changes. I am still open to improvements on this design!

🌐
GeeksforGeeks
geeksforgeeks.org › how-to-read-and-write-json-file-using-node-js
How to read and write JSON file using Node ? | GeeksforGeeks
January 7, 2025 - We can write data into a JSON file by using the nodejs fs module. We can use writeFile method to write data into a file. ... Example: We will add a new user to the existing JSON file, we have created in the previous example.
🌐
TestMu AI Community
community.testmuai.com › ask a question
Appending Data to JSON File in Node.js Without Overwriting - Ask a Question - TestMu AI Community
March 9, 2025 - How can I use Node.js to write JSON to a file while ensuring that new data is appended to the existing content instead of overwriting it? I want to generate a JSON file that stores an array of objects, each containing an ID and its square value. If the file already exists, new elements should be added ...
🌐
Andreas Wik
awik.io › write-append-file-node-js
Write To And Append To File With Node.js - Andreas Wik
August 10, 2023 - In order to append content to an already existing file, we simply use fs.appendFile instead, again passing in the filename, content and an error handler. fs.appendFile('people.json', people, error => { if (error) { console.error(error); } }); ...
🌐
Futurestud.io
futurestud.io › tutorials › node-js-write-a-json-object-to-a-file
Node.js — Write a JSON Object to a File - Future Studio
The following example uses the fs-extra package providing the Node.js file system API with full promise support and methods like copy(), remove(), mkdirs(). const Fs = require('fs-extra') async function writeToFile (path, data) { const json = JSON.stringify(data, null, 2) try { await Fs.writeFile(path, json) console.log('Saved data to file.') } catch (error) { console.error(error) } }
🌐
Attacomsian
attacomsian.com › blog › nodejs-write-json-object-to-file
How to read and write a JSON object to a file in Node.js
October 1, 2022 - try { fs.writeFileSync('user.json', data) console.log('JSON data is saved.') } catch (error) { console.error(err) } Be careful when you use synchronous file operations in Node.js.