좋아 나는이 JSON 파일이 있습니다읽고 Node.js를에서 JSON 파일을 작성
{
"joe": {
"name": "joe",
"lastName": "black"
},
"matt": {
"name": "matt",
"lastName": "damon"
}
}
을 나는 Node.js를 가진 사람을 추가 할 :
{
"joe": {
"name": "joe",
"lastName": "black"
},
"matt": {
"name": "matt",
"lastName": "damon"
},
"brad": {
"name": "brad",
"lastName": "pitt"
}
}
를 아래 코드로 json 문서를 읽고, 구문 분석하고, 사람을 추가 한 다음 다시 파일에 쓰려고합니다. 그러나 파싱 된 객체 (jsonObj)는 쓰기 함수에서 인식되지 않습니다. 이벤트 루프와 관련이 있다는 것을 알고 있지만 어떻게 해결해야할지 모르겠습니다. process.nextTick을 사용해 보았지만 작동시키지 못했습니다.
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;
}
});
});
});
잘 더 도움이 대답은 아니 ... 롤 – Mcs
아주 잘 작동하는의 setTimeout 될 것이다 setTimeout을 사용하지 마십시오 – david
setTimeOut (theWriteFunction, 100)을 읽는다면 왜 읽지 않습니다. 작동합니까? – Mcs