Mcs
Mcs

Reputation: 564

read and write a json file in node.js

okay I have this json file:

{   
    "joe": {
        "name": "joe",
        "lastName": "black"
    },

    "matt": {
        "name": "matt",
        "lastName": "damon"
    }
}

and I want to add a person with node.js:

{   
    "joe": {
        "name": "joe",
        "lastName": "black"
    },

    "matt": {
        "name": "matt",
        "lastName": "damon"
    },

    "brad": {
        "name": "brad",
        "lastName": "pitt"
    }
}

With the below code I am trying to read the json document, parse it, add the person, and then write again to file. However, the parsed object (jsonObj) is not recognized in the write function. I know it has to do with the event loop, but I am not sure how to solve it. I tried using process.nextTick, but can't get it to work.

var jsonObj;

fs.open('files/users.json', 'r+', function opened(err, fd) {
    if (err) {
        throw err;
    }
    var readBuffer = new Buffer(1024),
        bufferOffset = 0,
        readLength = readBuffer.length,
        startRead = 0; 
    fs.read(fd, readBuffer, bufferOffset, readLength, startRead, function read(err, readBytes) {
        if (err) {
            throw err;
        }
        if (readBytes > 0) {
            jsonObj = JSON.parse(readBuffer.slice(0, readBytes).toString());
            jsonObj["brad"] = {};
            jsonObj["brad"].name = "brad";
            jsonObj["brad"].lastName = "pitt";
        **//Until here it works fine and the 'jsonObj' is properly updated**
        }
    });
 });

process.nextTick(function () {
    var writeBuffer, 
        startWrite = 0,
        bufferPosition = 0,
        writeLength;
    fs.open('files/users.json', 'r+', function opened(err, fd) {
        if (err) {
            throw err;
        }
        ***//Below I get the 'jsonObj is undefined' error***
        writeBuffer = new Buffer(JSON.stringify(jsonObj.toString(), null, '/\t/'));
        writeLength = writeBuffer.length;
        fs.write(fd, writeBuffer, bufferPosition, writeLength, startWrite, function wrote(err, written) {
            if (err) {
                throw err;
            }
        });
    });
});

Upvotes: 2

Views: 5039

Answers (2)

Maroshii
Maroshii

Reputation: 4017

In node you can require json files:

var fs = require('fs');
var users = require('./names');

users.brad = {
  name: 'brad',
  lastName: 'pitt'
}

var string = JSON.stringify(users,null,'\t');

fs.writeFile('./names.json',string,function(err) {
  if(err) return console.error(err);
  console.log('done');
})

Optional async version without requiring:

var fs = require('fs');

fs.readFile('./names.json',{encoding: 'utf8'},function(err,data) {
  var users = JSON.parse(data);
   users.brad2 = { name: 'brad', lastName: 'pitt' };
  var string = JSON.stringify(users,null,'\t');

  fs.writeFile('./names.json',string,function(err) {
    if(err) return console.error(err);
    console.log('done');
  })  
})

Upvotes: 8

CFrei
CFrei

Reputation: 3627

The simple hint is: if you need to use process.nextTick, something is wrong. Leave that function to the library programmers! :)

Just move the function you call with nextTick to Until here...

nextTick does not wait until you read that file (that might take a few hundret ticks!), it just waits for the next tick. And that is available the nanosecond you call fs.read - because after fs.read the nodejs main loop is idle until either the kernel returns some information about that file or someone tells nodejs what to do on the next tick.

Upvotes: 2

Related Questions