Wednesday, 15 March 2017

JSON file in fs.writeFileSync not updating JSON file

This is my app.js:

var fs=require('fs');
var _=require('lodash');
var yargs=require('yargs');

var notes=require('./notes.js');
var argv=yargs.argv;

var command=argv._[0]
console.log("Command: "+command);

if(command==='add')
    {
        console.log('Adding Notes');
        notes.addNote(argv.title,argv.body);
    } else{
        console.log('command not found');
}

This is my notes.js:

const fs=require('fs');

var addNote=(title,body)=>{
    console.log('Adding note'+ title+' '+ body);
    var notes=[];
    var note={
        title,
        body
    };

    try{
        var noteString=fs.readFileSync('Realnotes-data.json');
        notes=JSON.parse(noteString);
    }catch(e){

    }
    notes.push(note);
    console.log(notes);
    fs.writeFileSync('Realnotes-data.json',JSON.stringify(notes));
};

module.exports={
    addNote
}

Now when on console I type: node app add --title="Secrets" --body="Secrets to success"
First time it is saved in Realnotes-data.JSON, but after that the JSON is not getting modified. If i console the notes array I am getting the whole array. But it is not updated in JSON.

Please Help...



via Nitesh Rana

No comments:

Post a Comment