javascript - 从 JSON 读取数据,对其进行操作并将其写回到 NodeJs 中

标签 javascript json node.js

我有一个包含此内容的小 JSON 文件

{
  "users": [
    {
      "id": 1111,
      "name": "Foo",
      "gold": 2
    },{
      "id": 2222,
      "name": "Bar",
      "gold": 7
    }
  ]
}

当使用 Ajax 时,我调用此路由

app.get('/incG/:id', function (req, res) {
  fs.writeFile('./database.json', 'utf8', function (err, data) {
    var json = JSON.parse(data); // get the data
    var users = json.users; // get all users
    var user = users.find(u => u.id === Number(req.params.id)); // get a user by id
    user.gold++; // increase his gold value
    res.send(user.gold); // send a response to the client
  });
});

运行服务器时我收到此错误消息

undefined:1
utf8
^

SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at ... \app.js:23:21
    at tryToString (fs.js:449:3)
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:436:12)

如何从文件中获取数据,更改通过其 id 选择的特定对象,将其写回文件并向客户端发送响应?

我的代码似乎是错误的,我想使用writeFile而不是readFile。我不想读取数据,我想操纵它。


编辑

我尝试构建此代码

app.get('/incG/:id', function (req, res) {
  var database = './database.json';
  var userId = Number(req.params.id);
  fs.readFile(database, 'utf8', function (err, data) {
    var json = JSON.parse(data);
    var users = json.users;
    var user = users.find(u => u.id === userId);
    user.gold++;
    fs.writeFile(database, json, (err) => {
      res.send(user.gold);
    });
  });
});

但我认为将 json 作为数据对象传递是错误的。文件内容被“破坏”

最佳答案

要写入文件,只需遵循 Node 文档即可:

app.get('/incG/:id', function (req, res) {
  fs.writeFile('./database.json', 'utf8', function (err, data) {

    var users = json.users; // get all users
    var user = users.find(u => u.id === Number(req.params.id));
    user.gold++; // increase his gold value

    fs.writeFile('database.json', myJSON, (err) => {
      if (err) throw err;
      res.send(user.gold);
    });
});

在网络服务器上读取文件/写入文件时,更好的方法是使用,这样您就不会在执行操作时消耗大量内存。

您可以在这篇精彩的文章中阅读更多相关信息:

关于javascript - 从 JSON 读取数据,对其进行操作并将其写回到 NodeJs 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47507472/

相关文章:

javascript - 来自 jQuery 的编程表单 POST 在文档就绪中不起作用

javascript - 用 Node.js 编写 JSON

node.js - Mongoose如何找到特定值

node.js - 如何使用node.js让Slack机器人在同一 channel 动态回复

javascript - 无法在函数内调用非内置函数

javascript - 如何将ajax响应/结果放入变量php

javascript - 单击同一表的其他 td 内的某些输入类型时获取表的 td 内容的值

javascript - Mathjs自定义求和函数

java - Jersey/Tomcat - 产生媒体冲突

java - 通过 JSON 解析器在 Java 中拆分和自定义字符串缓冲区?