Javascript 如何添加到 node.js 中的现有 json 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36093042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I add to an existing json file in node.js
提问by mmryspace
I am new to Node.js and JavaScript. I have a results.json
file that I want to keep a running log of results from a script that pulls images from the web. However, my current script only overwrites the existing result. How do I build upon or add to the results.json
so each subsequent result is logged in the results.json file? I would like it to be valid json.
我是 Node.js 和 JavaScript 的新手。我有一个results.json
文件,我想保留一个脚本的运行结果日志,该脚本从网络中提取图像。但是,我当前的脚本只会覆盖现有的结果。我如何构建或添加到results.json
以便每个后续结果都记录在 results.json 文件中?我希望它是有效的 json。
Here is general example:
这是一般示例:
var currentSearchResult = someWebSearchResult
var fs = require('fs');
var json = JSON.stringify(['search result: ' + currentSearchResult + ': ', null, "\t");
fs.writeFile("results.json", json);
And the results.json:
结果.json:
[
"search result: currentSearchResult"
]
采纳答案by Daniel Diekmeier
If you want the file to be valid JSON, you have to open your file, parse the JSON, append your new result to the array, transform it back into a string and save it again.
如果您希望文件是有效的 JSON,则必须打开文件,解析 JSON,将新结果附加到数组中,将其转换回字符串并再次保存。
var fs = require('fs')
var currentSearchResult = 'example'
fs.readFile('results.json', function (err, data) {
var json = JSON.parse(data)
json.push('search result: ' + currentSearchResult)
fs.writeFile("results.json", JSON.stringify(json))
})
回答by Daniel Diekmeier
In general, If you want to append to file you should use:
一般来说,如果你想附加到文件,你应该使用:
fs.appendFile("results.json", json , function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
Append file creates file if does not exist.
如果文件不存在,追加文件将创建文件。
But ,if you want to append JSON data first you read the data and after that you could overwrite that data.
但是,如果您想先附加 JSON 数据,您可以读取数据,然后您可以覆盖该数据。
fs.readFile('results.json', function (err, data) {
var json = JSON.parse(data);
json.push('search result: ' + currentSearchResult);
fs.writeFile("results.json", JSON.stringify(json), function(err){
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
})