从JSON中读取数据,操作并将其写回到NodeJs中

我有一个这个内容的小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) 

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

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


编辑

我试图build立这个代码

 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作为数据对象是错误的。 文件内容被“破坏”

要写入文件,只需遵循节点文档:

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

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

你可以在这篇文章中阅读更多关于它的信息:

我相信你错误地使用writeFile 。 根据Node.js文档 , writeFile的第二个参数应该是你想写的数据。 见下文:

 fs.writeFile('message.txt', 'Hello Node.js', (err) => { if (err) throw err; console.log('The file has been saved!'); });