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;
}
});
});
});