我正在尝试读取和写入JSON文件,但我在执行它时有点困难。当我迭代更多记录时,我正试图在JSON文件中追加新数据。
// scripts.js
var jsonFile = '../data/data.json';
var data = { "id": 0, "animal": "Dog" }, { "id": 1, "animal": "Cat" };
var readData = fs.read( jsonFile );
readData = readData.push( data );
fs.write( jsonFile, readData, 'a' );
-
我想要实现的目标
data.json
[]
data.json - 第一次迭代
[
{ "id": 0, "animal": "Dog" },
{ "id": 1, "animal": "Cat" }
]
data.json - 第二次迭代
[
{ "id": 0, "animal": "Dog" },
{ "id": 1, "animal": "Cat" },
{ "id": 2, "animal": "Owl" },
{ "id": 3, "animal": "Bat" }
]
答案 0 :(得分:2)
在运行此文件之前,将[]
放入'data.json'文件中。
const fs = require('fs-promise');
async function addRecord(jsonFile, row) {
const json = await fs.readFile(jsonFile,'utf8');
const rows = JSON.parse(json);
rows.push(row);
await fs.writeFile(jsonFile, JSON.stringify(rows));
}
async function test1() {
const jsonFile = 'data.json';
await addRecord(jsonFile, { "id": 0, "animal": "Dog" });
await addRecord(jsonFile, { "id": 1, "animal": "Cat" });
}
test1().catch(console.error);