如何读取/写入 node.js 中的 JSON 文件

iFl*_*ion 1 javascript json read-write

我对 node.js 相当陌生,我想知道如何(或什至是否)我可以读写 JSON 文件。我正在尝试创建一个可访问的惩罚历史。理想情况下,我希望能够按照以下方式创建一些东西:

{
"punishments": {
    "users": {
      "<example user who has a punishment history>": {
        "punishment-1567346": {
          "punishment-id": "1567346",
          "punishment-type": "mute",
          "punishment-reason": "<reason>"
        },
        "punishment-1567347": {
          "punishment-id": "1567347",
          "punishment-type": "ban",
          "punishment-reason": "<reason>"
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我将有办法访问格式化的惩罚历史记录。我真的不知道从哪里开始。

小智 7

您可以使用 NodeJS 内置库调用fs来执行读/写操作。

第 1 步 - 导入 fs

const fs = require('fs');
Run Code Online (Sandbox Code Playgroud)

第 2 步 - 读取文件

let rawdata = fs.readFileSync('punishmenthistory.json');
let punishments= JSON.parse(rawdata);
console.log(punishments);
Run Code Online (Sandbox Code Playgroud)

现在您可以使用该punishments变量来检查 JSON 文件中的数据。此外,您可以更改数据,但它目前仅驻留在变量中。

第 3 步 - 写入文件

let data = JSON.stringify(punishments);
fs.writeFileSync('punishmenthistory.json', data);
Run Code Online (Sandbox Code Playgroud)

完整代码:

const fs = require('fs');

let rawdata = fs.readFileSync('punishmenthistory.json');
let punishments= JSON.parse(rawdata);
console.log(punishments);

let data = JSON.stringify(punishments);
fs.writeFileSync('punishmenthistory.json', data);
Run Code Online (Sandbox Code Playgroud)

参考资料:https : //stackabuse.com/reading-and-writing-json-files-with-node-js/