gpt4 book ai didi

javascript - 尝试在 PhantomJS 上读写

转载 作者:行者123 更新时间:2023-12-01 03:51:23 27 4
gpt4 key购买 nike

我正在尝试读取和写入 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" }
]

最佳答案

在运行之前将 [] 放入文件“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);

关于javascript - 尝试在 PhantomJS 上读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43158640/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com