如何将数据推送到 JSON 文件中的数组并保存?

How can I push data to an array in a JSON file and save it?

所以我试图将一个数组推送到一个已经是数组格式的 JSON 文件。

The code im using to attempt this is:

needle.get("https://bpa.st/raw/VHVQ", function(response, body){
     let testlist = require('../testlist.json') 
     let list = response.body;
     let listarray = list.split("\r\n")
     for (var i of listarray) {
     testlist.push(i);
     }

当我的应用程序 运行 时,它显示 testlist.json 为:

["1", "2", "this", "is", "an", "example", "for", "Whosebug"]

现在它似乎工作正常,它就像它更新了数组一样,但如果我检查,它没有,如果我重新启动我的应用程序,它就会重置为原始的未编辑版本。

testlist.json looks like this:

["1", "2"]

之后,我试图让它编辑 json 文件,使其看起来像这样:

["1", "2", "this", "is", "an", "example", "for", "Whosebug"]

当您使用 require()testlist.json 的内容导入变量 testlist 时,您正在将文件的内容加载到内存中。如果您希望保留修改,则需要在对 testlist 变量进行更改后写回文件。否则,您所做的更改将在程序进程退出时丢失。

您可以使用 fs 模块中的 writeFileSync() 方法以及 JSON.stringify()testlist 写回 testlist.json 文件:

const fs = require("fs");

let testlist = require("../testlist.json");

// Your code where you modify testlist goes here

// Convert testlist to a JSON string
const testlistJson = JSON.stringify(testlist);
// Write testlist back to the file
fs.writeFileSync("../testlist.json", testlistJson, "utf8");

编辑:您还应该使用 readFileSync() 方法(也来自 fs 模块)和 JSON.parse() 来执行 JSON 文件的初始读取,而不是 require().

// This line
let testlist = require("../testlist.json");

// Gets replaced with this line
let testlist = JSON.parse(fs.readFileSync("../testlist.json", "utf8"));

您必须使用 JSON.parsefs.readFileSync,因为当您读取文件时,它是作为字符串读取的,而不是 JSON 对象。