[英]Have a JSON file on server with a Array of objects and want to push an object to it with fs.appendFile
我在服務器上有這個 JSON: [{"a":1}, {"a":2}]
並且想知道最后是否有添加一個對象,而不是在服務器上重寫整個文件。 我已經制定了解決方法,沒有括號,並在從服務器加載后添加它們。
newObj= {'a':3};
fs.appendFile(theServerFile, ',' + newObj, ...) ;
我會做以下事情:
const fs = require('fs');
fs.readFile('./jsonFile.html', function read(err, data) {
if (err) {
throw err;
}
processFile( JSON.parse(data) );
});
function processFile(data) {
data.push(newObj);
fs.writeFileSync('./jsonFile.html', data);
}
檢索當前內容,更新它並再次寫入。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.