所以,我正在开发具有一些功能的Discord机器人。我正在使用node.js和discord.js。我将代码分解为几个文件,因为它太长了,所以现在我需要一些东西来在函数之间传递全局变量并每次都进行更新。
我尝试的第一种方法是通过参数,但是其他函数的变量不会改变。
1。
async function prepare(message, parameters)
{
// Code here
}
对于第二种方法,我尝试使用JSON对象。要读取和更新值,我使用了readFile
和writeFile
。问题在于,在编写JSON对象时,某些数据会丢失,因为出于某些原因,值被简化,并且随后产生了错误。特别是,破坏的值来自ReactionCollector
对象。
2。
// Reads external JSON object.
let rawdata = fs.readFileSync('config.json');
let obj = JSON.parse(rawdata);
// do something with obj.
// Writes JSON object.
let data = JSON.stringify(obj);
fs.writeFileSync('config.json', data);
我最后一次尝试使用另一种类型的writeFile函数,该函数保留了数据,但是在多次读取JSON对象时却产生了问题。
3。
// Reads external JSON object.
const readFile = promisify(fs.readFile);
var data = await readFile('../config.json', { encoding: 'utf8' });
let obj = JSON.parse(data);
// Do something.
// Updates JSON object.
fs.writeFile('../config.json', packageJson, { encoding: 'utf8' }, err => {
if (err) throw err;
console.log("Wrote json.");
});
任何可以使此代码正常工作的人?
我发现最好,更简单的方法是对每个变量使用getter / setter函数。
这是一个示例:
var binary_tree = [];
function setBinary_tree(bt)
{
binary_tree = bt;
}
function getBinary_tree()
{
return binary_tree;
}
module.exports.setBinary_tree = setBinary_tree;
然后是将变量传递到外部文件的方式:
const { getBinary_tree, setBinary_tree } = require('./path/variables.js');
var binary_tree = getBinary_tree();
// Do something with the variable.
// At the end, updates the variables.
setBinary_tree(binary_tree);