在 Node.js 中导出变量的推荐方法

Recommended way to export variables in Node.js

我有一个 worker.js 文件,它定期更新几个变量的值。 在我的 Node.js 服务器的其他文件中,我想访问这些变量。

我知道如何导出它们,但它们似乎是按值导出的 - 即它们具有我发出 require 函数时的值。

当然,我很想了解他们的最新价值。 推荐的方法是什么? "getter" 函数还是其他?

通过引用导出它们的一种可能方法是实际操作 module.exports 对象 - 如下所示:

//worker.js
module.exports.exportedVar = 1;
var byValueVar = 2;

setInterval(foo, 2000);

function foo() {
    module.exports.exportedVar = 6;
    x = 8;
}

//otherfile.js
var worker = require('./worker');
console.log(worker.exportedVar); //1
console.log(worker.byValueVar) //2

setInterval(foo, 3000);

function foo() {
    console.log(worker.exportedVar); //6
    console.log(worker.byValueVar); //2
}