我想將物件格式陣列的資料附加到現有的 .json 檔案中,所以我已經為它撰寫了代碼,但是在 stackoverflow 上,我注意到很多開發人員建議在附加到現有 json 檔案之前先讀取檔案,然后將新資料推送到現有的 json 檔案。所以我遵循了這個并根據這個進行了更改,但得到了錯誤:
TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
用節點撰寫的代碼
newdata=[
{
UserId: '11',
UserName: 'harry',
},
{
UserId: 12,
UserName: 'David',
}
];
fs.readFile('results.json', function (err, data) {
if(data === '') {
json = JSON.parse(newdata);
json.push(newdata);
}
fs.writeFile("results.json", JSON.stringify(json));
})
uj5u.com熱心網友回復:
此錯誤是因為您以錯誤的方式使用.writeFile。
嘗試這樣的事情:
fs.writeFile('results.json', JSON.stringify(newData), function(err) {
if (err) throw err;
});
一個簡短的解釋:
錯誤訊息中的ERR_INVALID_CALLBACK是缺少上例中最后一個引數中通知的函式。
fs.writeFile(<file>, <content>, <callback>)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/416654.html
標籤:
上一篇:從For回圈生成的串列,帶有另一個JSON資料的.append()
下一篇:MongoDB 分片規則
