如何读取JSON文件,更改一些值并保存它.使用FS/Javascript



我的当前代码如下。

bot.on('message', mssg => {
io.emit('chat message', `${mssg.author.tag} - ${mssg.content}`);

var message = mssg.content.toLowerCase()
if(shydudearray.includes(message)) {
var newMsg = message.replace(" ", "");
fs.readFile('./assets/data/shydude.json', (err, data) => {
if (err) throw err;
let counter = JSON.parse(data);

x = counter[newMsg];
data[newMsg] = '2';

console.log(`Before: ${x}nAfter: ${counter[newMsg]}`)
});
}
});

我想获取我的JSON文件并获得当前数字,然后+1到当前数字,并将其保存到JSON文件中。使用FS/Javascript,我该如何让它发挥作用?

此处为

const fs = require('fs');
const filepath = './myJSONfile.json';
const data = JSON.parse(fs.readFileSync(filepath));
data[someKey] = "newValue";
fs.writeFileSync(filepath, JSON.stringify(data, null, 4));

PS:这是一个NodeJS问题,而不是JavaScript

从提问者编辑:修正变量错误

最新更新