我将尽力为您进行翻译。以下是需要翻译的内容:
我正在尝试在Node.js中向一个非常大的JSON文件中添加对象(但仅当id与现有对象不匹配时)。目前我的代码如下:
示例JSON文件:
[
{
id:123,
text: "some text"
},
{
id:223,
text: "some other text"
}
]
app.js
var fs = require('fs');
var jf = require('jsonfile')
var util = require('util')
var file = 'example.json'
// Example new object
var newThing = {
id: 324,
text: 'more text'
}
// Read the file
jf.readFile(file, function(err, obj) {
// Loop through all the objects in the array
for (i=0;i < obj.length; i++) {
// Check each id against the newThing
if (obj[i].id !== newThing.id) {
found = false;
console.log('thing ' + obj[i].id + ' is different. keep going.');
}else if (obj[i].id == newThing.id){
found = true;
console.log('found it. stopping.');
break;
}
}
// if we can't find it, append it to the file
if(!found){
console.log('could not find it so adding it...');
fs.appendFile(file, ', ' + JSON.stringify(newTweet) + ']', function (err) {
if (err) throw err;
console.log('done!');
});
}
})
这非常接近我想要的。唯一的问题是JSON文件末尾有一个括号]
,是否有办法使用文件系统API或其他方式删除它?或者有没有更简单的方法来实现我想要的目标?
jsonfile
模块仍然会将整个文件加载到内存中,所以您在这个阶段就有了问题。如果您已经能够负担将整个文件加载到内存中,那么Brad的解决方案将对您有所帮助。 - Darin Dimitrovobj.push(newThing);
。 - Darin Dimitrov