我有一个包含此内容的小 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/