javascript - Discord.js:我的代码不会将 2 个值加在一起
问题描述
首先,我只想说,感谢您花时间阅读本文;
我一直试图理解为什么我的代码在过去几个小时内不会将这两个值加在一起。
下面的代码首先检查发送消息的用户是否已经有一个文件,如果没有,则创建一个。然后它读取文件以获取用户拥有的 xp 值。然后它应该添加增益值(已注释掉,并在此处替换为 100,用于测试目的),但它似乎没有这样做,并且(最后)在第二次使用时将 100 写入文件命令,此时应该是 200。
也许我认为某些东西不起作用,而实际上它是我没有意识到的代码的另一部分?身份证。
如果您不明白我的意思,这里是使用该命令 3 次后出现在终端上的示例输出:
file exists
0
100
0
file @517812858688503818_xp.json (Leviah Deerie#0667) successfully written
file exists
0
100
100
file @517812858688503818_xp.json (Leviah Deerie#0667) successfully written
file exists
0
100
100
file @517812858688503818_xp.json (Leviah Deerie#0667) successfully written
// CODE BELOW //
// include server id in file writes names and such
const { networkInterfaces } = require('os');
module.exports = {
name: 'xprun',
description: "runs the xp handler",
execute(name, id) {
const fs = require('fs');
id = id.replace('<','');
id = id.replace('>','');
function jsonReader(filePath, cb) {
fs.readFile(filePath, 'utf-8', (err, fileData) => {
if (err) {
return cb && cb(err);
}
try {
const object = JSON.parse(fileData);
return cb && cb(null, object);
} catch (err) {
return cb && cb(err);
}
});
}
if (fs.existsSync(`./userData/xp/${id}_xp.json`)) {
console.log('file exists');
} else { // if the user doesn't have a file
console.log('creating new file');
const newObject = {
name: name,
id: id,
xp: 0,
level: 0,
rank: 0,
global: 0
}
fs.writeFile(`./userData/xp/${id}_xp.json`, JSON.stringify(newObject), err => {
if (err) {
console.log(err);
} else {
console.log(`file ${id}_xp.json (${name}) successfully written`);
}
});
}
// READ FILE
var xp = 0, level = 0, rank = 0, global = 0;
jsonReader(`./userData/xp/${id}_xp.json`, (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data.xp);
xp = data.xp;
level = data.level;
rank = data.rank;
global = data.global;
}
});
// EDIT VALUES
/*
const max = 10, min = 5;
const gain = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(xp);
console.log(gain);
// apply effects here
xp = xp + gain;
*/
console.log(xp);
xp = (parseInt(xp) + 100); // <------ ERRORS HERE
console.log(xp);
// WRITE FILE
const newObject = {
name: name,
id: id,
xp: xp,
level: level,
rank: rank,
global: global,
};
fs.writeFile(`./userData/xp/${id}_xp.json`, JSON.stringify(newObject), err => {
if (err) {
console.log(err);
} else {
console.log(`file ${id}_xp.json (${name}) successfully written`);
}
});
} // end execute
} // end
解决方案
推荐阅读
- spring-boot - Spring Cloud Contract + Pact(Broker):json字符串不能为null或为空
- java - 如何丢弃 JSpinner 的所有 InputMap 键绑定?
- amazon-web-services - 如何为通过 CSV 导入 AWS Neptune 的 Vertex 属性安排单基数?
- spring - Spring boot - 在某些情况下禁用验证注释
- sql - SQL - 授予整个公司的只读访问权限是不好的做法吗?
- mysql - SQL 从预订表中即时生成空闲插槽?
- javascript - 如何使用标头进行 POST 请求?
- java - 使用 Spring WebFlux 创建文本流
- javascript - 如何限制我的 node.js Swagger 服务器的堆栈跟踪?
- c# - 运行 MySql 存储过程的最低访问级别