[英]append json objects to file with nodejs
我只是想在調用某個函數后將json對象寫入文件(不一定是.json文件)。 當使用另一個json對象調用該函數時,我想將該對象附加到文件中。
目前,我正在使用jsonfile 。
var jsonfile = require('jsonfile');
...
users_file = "./users_file";
function update(user_json) {
jsonfile.writeFile(users_file,user_json), function(err) {
console.error(err);
});
}
但是使用另一個json對象再次調用update時,第一行將被覆蓋。
例:
json1 = {"id":123456,"first_name":"John","last_name":"Smith","username":"johnsmith"}
json2 = {"id":654321,"first_name":"marc","last_name":"cold","username":"marccold"}
當調用update(json1)
和更高版本的update(json2)
我希望文件看起來像這樣:
{"id":123456,"first_name":"John","last_name":"Smith","username":"johnsmith"}
{"id":654321,"first_name":"marc","last_name":"cold","username":"marccold"}
當前第二行正在替換第一行。 我嘗試先讀取文件,然后再連接兩個json對象,但是失敗了。 當文件為空時,這也需要工作。
使用appendFile()而不是writeFile()。 writeFile()用於寫入新文件或覆蓋現有文件(如果有)。 而appendFile()用於將Content附加到現有文件(如果有)或創建新文件並添加內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.