繁体   English   中英

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

[英]How to read/write to a JSON file in node.js

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

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

您可以使用名为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/

使用 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

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

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')
    }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM