如何读取、更新和传递位于不同 .js 文件中的函数之间的变量?

How to read, update and pass variables between functions that are placed in different .js files?

所以,我正在开发一个具有一些功能的 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.");
});

任何人都可以使此代码工作?

我发现最好和更简单的方法是对每个变量使用 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);