在多个文件 node.js 之间共享和修改变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17120117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sharing & modifying a variable between multiple files node.js
提问by thtsigma
main.js
主文件
var count = 1;
// psuedocode
// if (words typed begins with @add)
require('./add.js');
// if (words typed begins with @remove)
require('./remove.js');
// if (words typed begins with @total)
require('./total.js');
module.exports.count = count;
total.js
总计.js
var count = require('./main.js').count;
console.log(count);
add.js
添加.js
var count = require('./main.js').count;
count += 10;
console.log(count);
remove.js
删除.js
var count = require('./main.js').count;
count -= 10;
console.log(count);
console.log
控制台日志
1
11
-9
Background:
背景:
I have an application (irc bot), and I want to add a feature that peeps can do @add 1 or @remove 1. I have a main.js that then requires different files depending on the triggers that are said. So add would trigger the add.js file, and that would then require('main.js') and add 10 (10 for simplification, it'll actually parse the number and use that number) to it. The problem I'm having is when someone goes about and does @remove. It require('main.js') and subtracts 10 from 1 resulting in -9. And doing @total would output 1.
我有一个应用程序(irc bot),我想添加一个功能,peeps 可以执行 @add 1 或 @remove 1。我有一个 main.js,然后根据所说的触发器需要不同的文件。所以 add 将触发 add.js 文件,然后将 require('main.js') 并添加 10(为简化为 10,它实际上会解析数字并使用该数字)。我遇到的问题是当有人走动并执行@remove 时。它 require('main.js') 并从 1 中减去 10 结果为 -9。并且执行@total 将输出 1。
I've done a fairly good search for module.exports and I haven't come across an example like the one i listed above. The docsdon't include any examples close to what I'm wanting to do; and these questions 1, 2I understand--but aren't of any usefulness to me--as I understand what's being said there.
我已经对 module.exports 进行了相当好的搜索,但我没有遇到过像我上面列出的那样的例子。 文档不包含任何与我想要做的事情接近的示例;这些问题1、2我理解——但对我没有任何用处——因为我理解那里所说的。
Question:
题:
I'd like to have both @add and @remove manipulate the same variable ( count ), and for @total to return the total of count with the @add and @removes taken into account. Am I using module.exports incorrectly; or is there a common way that variables are shared, with one file being able to modify the contents of the module.exports and returning the results to the main.js file?
我想让 @add 和 @remove 操作同一个变量( count ),并且 @total 返回总计数并考虑 @add 和 @removes 。我是否错误地使用了 module.exports;或者是否有一种共享变量的通用方式,一个文件能够修改 module.exports 的内容并将结果返回到 main.js 文件?
回答by MiniGod
Your problem is that when you do var count = require('./main.js').count;, you get a copy of that number, not a reference. Changing countdoes not change the "source".
您的问题是,当您这样做时var count = require('./main.js').count;,您会得到该号码的副本,而不是参考。改变count不会改变“源”。
However, you should have the files export functions. Requiring a file will only run it the first time, but after that it's cached and does not re-run. see docs
但是,您应该具有文件导出功能。需要一个文件只会在第一次运行它,但之后它会被缓存并且不会重新运行。查看文档
Suggestion #1:
建议#1:
// main.js
var count = 1;
var add = require('./add.js');
count = add(count);
// add.js
module.exports = function add(count) {
return count+10;
}
#2:
#2:
var count = 1;
var add = function() {
count += 10;
}
add();
#3: Personally i would create a counter module (this is a single instance, but you can easily make it a "class"):
#3:我个人会创建一个计数器模块(这是一个单一的实例,但你可以很容易地把它变成一个“类”):
// main.js
var counter = require('./counter.js');
counter.add();
console.log(counter.count);
// counter.js
var Counter = module.exports = {
count: 1,
add: function() {
Counter.count += 10;
},
remove: function() {
Counter.count += 10;
}
}
回答by Jamie Hutber
Not sure if this new or not but you can indeed share variables between files as such:
不确定这是否是新的,但您确实可以在文件之间共享变量,例如:
main.js
主文件
exports.main = {
facebook: null
};
counter.js
计数器.js
var jamie = require('./main');
console.info(jamie); //{facebook: null}
jamie.main.facebook = false;
console.info(jamie); //{facebook: false}
anothercheck.js
另一个检查.js
var jamie = require('./main');
console.info(jamie); //{facebook: null} //values aren't updated when importing from the same file.
jamie.main.facebook = true;
console.info(jamie); //{facebook: true}
Now you can share between files.
现在您可以在文件之间共享。
回答by Yudhi Armyndharis
I have same problem like you,.. Sometimes I'd like to sharing variables between multiple files because I love modular style eg. separating controller, function, models in different folders/files on my node.js script so I can easy manage the code.
我和你有同样的问题,.. 有时我想在多个文件之间共享变量,因为我喜欢模块化风格,例如。在 node.js 脚本的不同文件夹/文件中分离控制器、函数、模型,以便我可以轻松管理代码。
I don't know if this is the best solution but I hope will suit your needs.
我不知道这是否是最好的解决方案,但我希望能满足您的需求。
models/data.js
模型/data.js
// exports empty array
module.exports = [];
controllers/somecontroller.js
控制器/somecontroller.js
var myVar = require('../models/data');
myVar.push({name: 'Alex', age: 20});
console.log(myVar);
// [{ name: 'Alex', age: 20 }]
controllers/anotherController.js
控制器/anotherController.js
var myVar = require('../models/data');
console.log(myVar);
// This array has value set from somecontroller.js before...
// [{ name: 'Alex', age: 20 }]
// Put new value to array
myVar.push({name: 'John', age: 17});
console.log(myVar);
// Value will be added to an array
// [{ name: 'Alex', age: 20 }, { name: 'John', age: 17}]
回答by Jacob Schneider
A little hack that works but isn't recommended is using the processvariable. You can apply different properties to it and essentially use them like you would the windowobject in browser-based JS. This little hack will provide a reference to the variable. It can be changed and manipulated and the change will carry over to all files that are required.
一个可行但不推荐的小技巧是使用process变量。您可以对它应用不同的属性,并基本上像window在基于浏览器的 JS 中使用对象一样使用它们。这个小技巧将提供对变量的引用。它可以更改和操作,更改将延续到所有required文件。
But do note that it is not recommended as overriding the
processvariable could have some unexpected effects and is subject to loss of information should another process interfere.
但请注意,不建议这样做,因为覆盖
process变量可能会产生一些意想不到的影响,并且如果另一个进程干扰,可能会丢失信息。
file1.js:
文件1.js:
const s1 = require('./file2');
process.num = 2;
console.log("file1", process.num);
s1.changeNum();
console.log("file1", process.num);
file2.js:
file2.js:
module.exports.changeNum = () => {
process.num = 3;
console.log("file2", process.num);
};
output:
输出:
file1 2
file2 3
file1 3
file1 2
file2 3
file1 3
回答by Ooo
There is no way you can share a reference between different files. You shouldn't be.
您无法在不同文件之间共享参考。你不应该。
I have a main.js that then requires different files depending on the triggers that are said
我有一个 main.js 然后根据所说的触发器需要不同的文件
I don't think that's a good idea. All require statements you'll ever need must be at the top of the file.
我不认为这是个好主意。您需要的所有 require 语句都必须位于文件的顶部。
I also see that You're requiring main.jsin total.jsand total.jsin main.js. The require()function imports the module.exportsof the file and assigns it to the namespace you provide. Your code shouldn't be split into files this way. You extract code into separate files only when they're modules by themselves. And if you do, you wouldn't be importing 2 files on each other.
我还看到你需要main.jsintotal.js和total.jsin main.js。该require()函数导入module.exports文件的 并将其分配给您提供的命名空间。您的代码不应该以这种方式拆分成文件。只有当它们本身是模块时,您才将代码提取到单独的文件中。如果这样做,您就不会相互导入 2 个文件。
It is also good to note that in javascript, when you assign something to a namespace, It gets copied (cloned) if it's a primitive. If it's an object, both namespaces then refer to the same object
还需要注意的是,在 javascript 中,当您将某些内容分配给命名空间时,如果它是原始类型,则会被复制(克隆)。如果它是一个对象,则两个命名空间都指向同一个对象
var num = 5;
var prim = num;
prim++; // prim is 6, but num is still 5.
var num = {five:5};
var ob = num;
ob.five = 6;
console.log(num.five) //also 6.
回答by Aditya Shankar
alternatively, to all other answers
或者,对于所有其他答案
getters& setters
吸气和setter方法
var _variableThing = 1223
module.exports = {
get variableThing(){
return _variableThing
},
set variableThing(val){
_variableThing = val
}
}
won't work with direct imports though
虽然不适用于直接导入

