311

I am trying to write JSON file using node from loop data, e.g.:

let jsonFile = require('jsonfile');

for (i = 0; i < 11; i++) {
    jsonFile.writeFile('loop.json', "id :" + i + " square :" + i * i);
}

outPut in loop.json is:

id :1 square : 1

but I want output file like this (below) and also if I run that code again it should add that new output as elements in same existing JSON file:

{
   "table":[
      {
         "Id ":1,
         "square ":1
      },
      {
         "Id ":2,
         "square ":3
      },
      {
         "Id ":3,
         "square ":9
      },
      {
         "Id ":4,
         "square ":16
      },
      {
         "Id ":5,
         "square ":25
      },
      {
         "Id ":6,
         "square ":36
      },
      {
         "Id ":7,
         "square ":49
      },
      {
         "Id ":8,
         "square ":64
      },
      {
         "Id ":9,
         "square ":81
      },
      {
         "Id ":10,
         "square ":100
      }
   ]
}

I want to use same file that I created 1st time but whenever I run that code new elements should add in that same file

const fs = require('fs');

let obj = {
    table: []
};

fs.exists('myjsonfile.json', function(exists) {

    if (exists) {

        console.log("yes file exists");

        fs.readFile('myjsonfile.json', function readFileCallback(err, data) {

            if (err) {
                console.log(err);
            } else {
                obj = JSON.parse(data);

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

                let json = JSON.stringify(obj);
                fs.writeFile('myjsonfile.json', json);
            }
        });
    } else {

        console.log("file not exists");

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

        let json = JSON.stringify(obj);
        fs.writeFile('myjsonfile.json', json);
    }
});
Mike
  • 14,010
  • 29
  • 101
  • 161
Isoftmaster
  • 3,175
  • 2
  • 11
  • 15

9 Answers9

569

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.

kailniris
  • 8,856
  • 2
  • 17
  • 24
  • 2
    Or you can also use the [jsonfile](https://www.npmjs.com/package/jsonfile) Node package which wraps all the complexities not shown in the code above. – Jeach Jan 24 '19 at 19:33
  • if you want to pretty print it: ** `const fsp = require('fs').promises; const json = JSON.stringify(matterData, null, 4); await fsp.writeFile('all-matter.data', json, "utf8");'** don't forget that you need to put it in an [async](https://mzl.la/3hRtL4o) function if you want to use **await**.. – ccalvert Mar 08 '22 at 23:01
52

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.

Jacob Nelson
  • 2,370
  • 23
  • 35
30

For synchronous approach

const fs = require('fs')
fs.writeFileSync('file.json', JSON.stringify(jsonVariable));
Jesse Reza Khorasanee
  • 3,140
  • 4
  • 36
  • 53
Nirojan Selvanathan
  • 10,066
  • 5
  • 61
  • 82
26

try

var fs = require("fs");
var sampleObject = { your data };

fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
    if (err) {  console.error(err);  return; };
    console.log("File has been created");
});
16

you should read the file, every time you want to add a new property to the json, and then add the the new properties

var fs = require('fs');
fs.readFile('data.json',function(err,content){
  if(err) throw err;
  var parseJson = JSON.parse(content);
  for (i=0; i <11 ; i++){
   parseJson.table.push({id:i, square:i*i})
  }
  fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
    if(err) throw err;
  })
})
Zamboney
  • 2,002
  • 12
  • 22
  • 1
    thanks for reply i tried its working but how to check if old file is exists then run readlfile code else run writeFile direct to create new file i am creating daily new file with current date in file name and i want new data to be add in that old file whole day when this code run – Isoftmaster Apr 26 '16 at 18:00
15

Above example is also correct, but i provide simple example:

var fs = require("fs");
var sampleObject = {
    name: 'pankaj',
    member: 'stack',
    type: {
        x: 11,
        y: 22
    }
};

fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
    if (err) {
        console.error(err);
        return;
    };
    console.log("File has been created");
});
Pankaj Chauhan
  • 1,623
  • 14
  • 12
9

For formatting jsonfile gives spaces option which you can pass as a parameter:

   jsonfile.writeFile(file, obj, {spaces: 2}, function (err) {
         console.error(err);
   })

Or use jsonfile.spaces = 4. Read details here.

I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop.

var jsonfile = require('jsonfile');
var obj={
     'table':[]
    };

for (i=0; i <11 ; i++){
       obj.table.push({"id":i,"square":i*i});
}
jsonfile.writeFile('loop.json', obj, {spaces:2}, function(err){
      console.log(err);
});
avck
  • 3,535
  • 3
  • 26
  • 38
2

I agree with above answers, Here is a complete read and write sample for anyone who needs it.

     router.post('/', function(req, res, next) {

        console.log(req.body);
        var id = Math.floor((Math.random()*100)+1);

        var tital = req.body.title;
        var description = req.body.description;
        var mynotes = {"Id": id, "Title":tital, "Description": description};
        
        fs.readFile('db.json','utf8', function(err,data){
            var obj = JSON.parse(data);
            obj.push(mynotes);
            var strNotes = JSON.stringify(obj);
            fs.writeFile('db.json',strNotes, function(err){
                if(err) return console.log(err);
                console.log('Note added');
            });

        })
        
        
    });


  
MJ X
  • 8,506
  • 12
  • 74
  • 99
2

Promise based solution [Javascript (ES6) + Node.js (V10 or above)]

Write to the File:

const fsPromises = require('fs').promises; 
fsPromises.writeFile('myFile.json', JSON.stringify({ name: "Sridhar", salary: 1234 }))
        .then( () => { console.log('JSON saved'); })
        .catch(er => { console.log(er);});

Append to the File:

const fsPromises = require('fs').promises;
fsPromises.readFile('myFile.json', 'utf8') 
        .then(data => { 
                let json = JSON.parse(data);
                json.myArr.push({name: "Krishnan", salary: 5678});

                fsPromises.writeFile('myFile.json', JSON.stringify(json))
                        .then(  () => { console.log('Append Success'); })
                        .catch(err => { console.log("Append Failed: " + err);});
            })
        .catch(err => { console.log("Read Error: " +err);});

If your project supports Javascript ES8 then you could use asyn/await instead of native promise.

SridharKritha
  • 8,481
  • 2
  • 52
  • 43