![](/img/trans.png)
[英]Have a JSON file on server with a Array of objects and want to push an object to it with fs.appendFile
[英]json file not updating properly with appendfile
我正在使用以下代碼將數據發布到json文件:
let productObj= {
description: req.body.description,
quality: req.body.quality
};
fs.readFile('products.json', function (err, data) {
let jsone= JSON.stringify(productObj);
console.log(jsone);
fs.appendFile("results.json", jsone, function(err){
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
});
});
我在控制台中看到POST成功,但是在json文件中,數據被附加到son對象外部。
products.json:
{
"products":[
{
"description": "Apples",
"quality": "High",
},
{
"description": "Oranges",
"quality": "low",
}
]}
appendFile
將現有內容與新內容連接在一起。 假設以下內容:
ABC
XYZ
ABCXYZ
在您的情況下,內容類型是JSON,需要采用某種appendFile
是與contentType
無關的,這意味着您必須正確格式化/合並現有數據集與新數據集,然后將其保存回文件中。
嘗試下一個代碼
let productObj= {
description: req.body.description,
quality: req.body.quality
};
fs.readFile('products.json', function (err, data) {
// Convert string (old data) to JSON
let result = JSON.parse(data);
// Add new data to result
result.products.push(productObj);
// Convert JSON to string
let jsone= JSON.stringify(result);
console.log(jsone);
// Replace all data in the results.json with new ones
fs.writeFile("results.json", jsone, function(err){
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
});
fs.appendFile
對文件的json結構一無所知,它將所有文件視為文本(或二進制)。
有兩種解決方案:
每個請求,讀取結果文件,將其解析為json,將元素壓入數組的末尾,然后使用fs.writeFile
替換磁盤上的文件。 這種方法使用json,但不是很可靠,因為隨着文件的增大,它會變慢,並且如果同時發出多個請求,它會中斷。
第二種選擇是不使用JSON。 而是使用如下所示的基於文本的結構。 這樣,您就可以根據需要自由地直接將其直接附加到磁盤上。 如果同時收到請求,這種方法不會中斷,並且無論結果文件有多大,它都將保持相同的速度。
Apples High
Oranges Low
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.