如何在放置在不同.js文件中的函数之间读取,更新和传递变量?

问题描述 投票:0回答:1

所以,我正在开发具有一些功能的Discord机器人。我正在使用node.js和discord.js。我将代码分解为几个文件,因为它太长了,所以现在我需要一些东西来在函数之间传递全局变量并每次都进行更新。

我尝试的第一种方法是通过参数,但是其他函数的变量不会改变。

1。

async function prepare(message, parameters)
{
  // Code here
}

对于第二种方法,我尝试使用JSON对象。要读取和更新值,我使用了readFilewriteFile。问题在于,在编写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.");
});

任何可以使此代码正常工作的人?

node.js function variables discord.js global
1个回答
0
投票

我发现最好,更简单的方法是对每个变量使用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);
© www.soinside.com 2019 - 2024. All rights reserved.