【问题标题】:Failed to append data in .json file using node无法使用节点在 .json 文件中追加数据
【发布时间】:2022-01-19 19:30:38
【问题描述】:

我想将对象格式数组的数据附加到现有的 .json 文件中,因此我已经为其编写了代码,但是在 stackoverflow 上,我注意到很多开发人员建议在附加到现有 json 文件之前先读取文件然后推送现有 json 文件的新数据。所以我遵循了这个并根据这个进行了更改,但得到了错误:

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined

节点中编写的代码

 newdata=[
  {
    UserId: '11',
    UserName: 'harry',
   
  },
  {
    UserId: 12,
    UserName: 'David',
  }
];

     fs.readFile('results.json', function (err, data) {
    if(data === '') {
        json = JSON.parse(newdata);
        json.push(newdata);
    }
    fs.writeFile("results.json", JSON.stringify(json));
  })

【问题讨论】:

标签: javascript node.js json fs readfile


【解决方案1】:

这个错误是因为你以错误的方式使用了.writeFile

试试这样的:

fs.writeFile('results.json', JSON.stringify(newData), function(err) {
    if (err) throw err; 
});

简短说明:

错误信息中的ERR_INVALID_CALLBACK是上例中最后一个参数通知的函数缺失。

fs.writeFile(<file>, <content>, <callback>)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多