【问题标题】:How to read/write to a JSON file in node.js如何在 node.js 中读取/写入 JSON 文件
【发布时间】:2020-11-06 12:39:14
【问题描述】:

我对 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>"
        }
      }
    }
  }
}

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

【问题讨论】:

标签: javascript json read-write


【解决方案1】:

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

第 1 步 - 导入 fs

const fs = require('fs');

第 2 步 - 读取文件

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

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

第 3 步 - 写入文件

let data = JSON.stringify(punishments);
fs.writeFileSync('punishmenthistory.json', data);

完整代码:

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);

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

【讨论】:

    【解决方案2】:

    使用 NodeJS 文件系统https://nodejs.org/dist/latest-v14.x/docs/api/fs.html

    这里我使用writeFileSync API 写入文件和readFileSync 读取文件。另外,在写入时不要忘记JSON.stringify(data),因为您正在将数据写入 JSON 文件。

    const fs = require("fs");
    const path = require("path");
    
    // Write Data
    const data = {
    "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>"
            }
          }
        }
      }
    };
    
    fs.writeFileSync(path.join(__dirname, "outputfilepath", "outputfile.json"), JSON.stringify(data), "utf8");
    
    // Read data
    const rData = fs.readFileSync(path.join(__dirname, "outputfilepath", "outputfile.json"), "utf8");
    const jsonData = JSON.parse(rData);
    

    这是一个工作示例, https://repl.it/repls/OutrageousInbornBruteforceprogramming#index.js

    【讨论】:

      【解决方案3】:

      你可以做这样的事情来阅读:

      const fs = require('fs')
      function jsonReader(filePath, cb) {
          fs.readFile(filePath, (err, fileData) => {
              if (err) {
                  return cb && cb(err)
              }
              try {
                  const object = JSON.parse(fileData)
                  return cb && cb(null, object)
              } catch(err) {
                  return cb && cb(err)
              }
          })
      }
      jsonReader('./customer.json', (err, customer) => {
          if (err) {
              console.log(err)
              return
          }
          console.log(customer.address) // => "Infinity Loop Drive"
      })
      

      喜欢这样写:

      const fs = require('fs')
      const customer = {
          name: "Newbie Co.",
          order_count: 0,
          address: "Po Box City",
      }
      const jsonString = JSON.stringify(customer)
      fs.writeFile('./newCustomer.json', jsonString, err => {
          if (err) {
              console.log('Error writing file', err)
          } else {
              console.log('Successfully wrote file')
          }
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-08
        • 2013-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-13
        • 2020-06-06
        • 1970-01-01
        相关资源
        最近更新 更多