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
608

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
Say you have a customer.json file saved to disk that holds a record for a customer in your store. As part of your store app, you want to access the customer’s address, and then update the order count after an order is placed. In this tutorial, we are going to look at how to read and write to our customer.json file.
🌐
LogRocket
blog.logrocket.com › home › reading and writing json files in node.js: a complete tutorial
Reading and writing JSON files in Node.js: A complete tutorial - LogRocket Blog
November 1, 2024 - JSON.stringify will format your JSON data in a single line if you do not pass the optional formatting argument to the JSON.stringify method specifying how to format your JSON data. To write a JSON file, the fs module is also required.
🌐
Medium
medium.com › devcodesights › how-to-read-and-write-json-files-in-node-js-step-by-step-instructions-a42bdb193685
How to Read and Write JSON Files in Node.js: Step-by-Step | devCodeSights
October 20, 2024 - Learn how to efficiently read and write JSON files in Node.js with our step-by-step guide. Master JSON handling for APIs, configuration, and data storage to enhance your Node.js applications.
🌐
Stack Abuse
stackabuse.com › reading-and-writing-json-files-with-node-js
Reading and Writing JSON Files with Node.js
July 8, 2024 - You can also use the global require ... from files with .json extension. Similarly, the writeFile and writeFileSync functions from the fs module write JSON data to the file in an asynchronous and synchronous manner respectively....
🌐
npm
npmjs.com › package › write-json-file
write-json-file - npm
Latest version: 7.0.0, last published: 5 months ago. Start using write-json-file in your project by running `npm i write-json-file`. There are 392 other projects in the npm registry using write-json-file.
      » npm install write-json-file
    
Published   Sep 14, 2025
Version   7.0.0
Author   Sindre Sorhus
🌐
CodeSignal
codesignal.com › learn › courses › hierarchical-and-structured-data-formats-in-ts › lessons › writing-json-files-using-typescript-and-nodejs
Writing JSON Files Using TypeScript and Node.js
Using JSON.stringify with null and 4 for spacing creates human-readable JSON files that are helpful for debugging and inspection. However, for a compact file, omit the spacing: ... In this lesson, you learned how to construct TypeScript objects and write them to a JSON file using Node.js's fs module.
Find elsewhere
🌐
npm
npmjs.com › package › jsonfile
jsonfile - npm
You can use fs.writeFile option { flag: 'a' } to achieve this. const jsonfile = require('jsonfile') const file = '/tmp/mayAlreadyExistedData.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj, { flag: 'a' }, function (err) { if (err) ...
      » npm install jsonfile
    
Published   Aug 12, 2025
Version   6.2.0
Author   JP Richardson
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › node › json to file
Node.js - How can I save a JSON object to a file using JavaScript? - 30 seconds of code
February 1, 2024 - To convert the JSON object to a string, you can use JSON.stringify(). Finally, you should specify the file extension as .json. import { writeFileSync } from 'fs'; const JSONToFile = (obj, filename) => writeFileSync(`${filename}.json`, JSON.stringify(obj, null, 2)); JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json'
🌐
GitHub
github.com › jprichardson › node-jsonfile
GitHub - jprichardson/node-jsonfile: Easily read/write JSON files.
You can use fs.writeFile option { flag: 'a' } to achieve this. const jsonfile = require('jsonfile') const file = '/tmp/mayAlreadyExistedData.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj, { flag: 'a' }, function (err) { if (err) ...
Starred by 1.2K users
Forked by 389 users
Languages   JavaScript 100.0% | JavaScript 100.0%
🌐
TutorialKart
tutorialkart.com › nodejs › node-js-write-json-object-to-file
Node.js Write JSON Object to File - Example
November 29, 2020 - To save the JSON object to a file, we stringify the json object jsonObj and write it to a file using Node FS’s writeFile() function. nodejs-write-json-object-to-file.js ·
🌐
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 - You can use the JSON.stringify() method to convert your JSON object into its string representation, and then use the file system fs module to write it to a file.
🌐
YouTube
youtube.com › watch
Write a JSON File with NodeJS - YouTube
With NodeJS, you can write your own files with built-in modules. In this video, I'll show you how to create JSON files with NodeJS and a few npm packages. Yo...
Published   October 12, 2021
🌐
DEV Community
dev.to › michaelburrows › how-to-read-and-write-json-files-using-nodejs-413a
How to read and write JSON files using Node.js - DEV Community
February 28, 2023 - JSON is a lightweight format for storing and transporting data. Because JSON is easy to read and write it’s used by many programming languages not just JavaScript. In this tutorial I’ll show you how to read and write JSON files using Node.js.
🌐
Attacomsian
attacomsian.com › blog › nodejs-read-write-json-files
How to read and write JSON files in Node.js
October 1, 2022 - Learn how to read and write JSON files in Node.js by using the native File System module, the require() method, and the jsonfile module.
🌐
Stack Overflow
mariokandut.com › how to read and write json files with node.js?
How to read and write JSON Files with Node.js?
March 21, 2022 - Similar to parsing data into an object when reading, we have to transform data into a string to be able to write it to a file. We have to create a JSON string of the javascript object with the global helper method JSON.stringify.
🌐
Futurestud.io
futurestud.io › tutorials › node-js-write-a-json-object-to-a-file
Node.js — Write a JSON Object to a File
JavaScript comes with the JSON class that lets you serialize an object to JSON with JSON.stringify. The file system fs module then writes data to the disk.
🌐
Medium
medium.com › @mariokandut › how-to-read-and-write-json-files-with-node-js-d7733c641aab
How to read and write JSON Files with Node.js? | by Mario Kandut | Medium
May 16, 2021 - Similar to parsing data into an object when reading, we have to transform data into a string to be able to write it to a file. We have to create a JSON string of the javascript object with the global helper method JSON.stringify.
🌐
DEV Community
dev.to › mariokandut › how-to-read-and-write-json-files-with-node-js-35j0
How to read and write JSON Files with Node.js? - DEV Community
May 17, 2021 - Similar to parsing data into an object when reading, we have to transform data into a string to be able to write it to a file. We have to create a JSON string of the javascript object with the global helper method JSON.stringify.