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.

Answer from kailniris on Stack Overflow
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.

🌐
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. 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
Appending Data to JSON File in Node.js Without Overwriting - Ask a Question - TestMu AI Community
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 ... More on community.testmuai.com
🌐 community.testmuai.com
0
March 9, 2025
🌐
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 - var fs = require('fs') fs.readFile('./users.json', 'utf-8', function(err, data) { if (err) throw err var arrayOfObjects = JSON.parse(data) arrayOfObjects.users.push({ name: "Mikhail", age: 24 }) console.log(arrayOfObjects) }) ... You can appended any objects to users array. After we have data in variable we need to write this into file:
🌐
HeyNode
heynode.com › tutorial › readwrite-json-files-nodejs
Read/Write JSON Files with Node.js | HeyNode
Now we have the contents of the file as a JSON string, but we need to turn the string into an object. Before we can use the data from the callback in our code, we must turn it into an object. JSON.parse takes JSON data as input and returns a new JavaScript object.
Find elsewhere
🌐
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 - Add the data using .push() method. Write the new data to the file using JSON.stringify() method to convert data into string.
🌐
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 - Can also pass in spaces, or override EOL string or set finalEOL flag as false to not save the file with EOL at the end. const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj) formatting with spaces: const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj, { spaces: 2 }) overriding EOL: const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj, { spaces: 2, EOL: '\r\n' }) disabling the EOL at the end of file: const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj, { spaces: 2, finalEOL: false }) appending to an existing JSON file: You can use fs.writeFileSync option { flag: 'a' } to achieve this.
      » npm install jsonfile
    
Published   Aug 12, 2025
Version   6.2.0
Author   JP Richardson
🌐
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 in software applications, and especially JavaScript-based applications, it is important to know how to read and 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 text to it:
🌐
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.
🌐
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
const Fs = require('fs') function writeToFile (data, path) { const json = JSON.stringify(data, null, 2) Fs.writeFile(path, json, (err) => { if (err) { console.error(err) throw err } console.log('Saved data to file.') }) } The callback gives you a single error parameter. Add error handling for cases where the file writing process went wrong.
🌐
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.
🌐
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!

🌐
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 ...
🌐
Andreas Wik
awik.io › write-append-file-node-js
Write To And Append To File With Node.js - Andreas Wik
August 10, 2023 - fs.appendFile('people.json', people, error => { if (error) { console.error(error); } }); If you open the file you wrote to now you should see the new data at the end of it.
Top answer
1 of 2
5

Try this. Don't forget to define anchors array.

var data = fs.readFileSync('testOutput.json');
var json = JSON.parse(data);
json.push(...anchors);

fs.writeFile("testOutput.json", JSON.stringify(json))
2 of 2
0

I created two small functions to handle the data to append.

  1. the first function will: read data and convert JSON-string to JSON-array
  2. then we add the new data to the JSON-array
  3. we convert JSON-array to JSON-string and write it to the file

example: you want to add data { "title":" 2.0 Wireless " } to file my_data.json on the same folder root. just call append_data (file_path , data ) ,

it will append data in the JSON file, if the file existed . or it will create the file and add the data to it.

data = {  "title":"  2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )

the full code is here :

   const fs = require('fs');
   data = {  "title":"  2.0 Wireless " }
   file_path = './my_data.json'
   append_data (file_path , data )

   async function append_data (filename , data ) {

    if (fs.existsSync(filename)) {
        read_data = await readFile(filename)
        if (read_data == false) {
            console.log('not able to read file')
        }
        else {
            read_data.push(data)
            dataWrittenStatus = await writeFile(filename, read_data)
            if dataWrittenStatus == true {
              console.log('data added successfully')
            }
           else{
              console.log('data adding failed')
            }
        }
      else{
          dataWrittenStatus = await writeFile(filename, [data])
          if dataWrittenStatus == true {
              console.log('data added successfully')
          }
          else{
             console.log('data adding failed')
           }
      }
   }



    async function readFile  (filePath) {
      try {
        const data = await fs.promises.readFile(filePath, 'utf8')
        return JSON.parse(data)
      }
     catch(err) {
         return false;
      }
    }

    async function writeFile  (filename ,writedata) {
      try {
          await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');
          return true
      }
      catch(err) {
          return false
      }
    }
🌐
Attacomsian
attacomsian.com › blog › nodejs-read-write-json-files
How to read and write JSON files in Node.js
October 1, 2022 - We can combine these approaches to use our JSON files as a simple database. Whenever we want to update the JSON file, we can read the contents, change the data, and then write the new data back to the original file. Here is an example that demonstrates how you can add another record to the databases.json file: