我有一个小的 JSON 文件
{
"users": [
{
"id": 1111,
"name": "Foo",
"gold": 2
},{
"id": 2222,
"name": "Bar",
"gold": 7
}
]
}
并希望操作一个特定对象的数据,由其 id 选择。
我要
- 从文件中读取数据
- 处理数据
- 将新数据写回文件
- 向客户端发送响应
所以我选择了这条路线,使用 Ajax 调用
app.get('/incG/:id', function (req, res) {
fs.readFile('./database.json', 'utf8', function (err, data) {
var json = JSON.parse(data); // Read the data
var users = json.users; // Get all users
var user = users.find(u => u.id === Number(req.params.id)); // get the user by id
user.gold++; // increase his value
fs.writeFile('./database.json', , (err) => { // the second parameter is missing!
res.send(user.gold); // send a response to the client
});
});
});
如您所见,在使用 fs.writeFile(database, , (err) => {
时缺少第二个参数。
我必须在那里传递什么?我只想更新一个特定的用户对象(一个特定的值)。
编辑
当传入 JSON.stringify(user)
作为参数时,我删除了文件中的所有数据,只写下新对象。所以这种方式可能行不通。
最佳答案
试试这个,
fs.readFile('./database.json', 'utf8', function (err, data) {
var json = JSON.parse(data); // Read the data
var users = json.users; // Get all users
var userGold;
users.find(u => {
if (u.id === Number(req.params.id)) {
userGold = u.gold++;
}
});
users = JSON.stringify(users);
fs.writeFile('./database.json', users, (err) => {
res.send(userGold);
});
});
关于javascript - 使用 NodeJs 中的文件系统模块更新 JSON 文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47508495/