Javascript 如何将变量传递给 NodeJS 模块?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28380561/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:42:42  来源:igfitidea点击:

How to pass variables into NodeJS modules?

javascriptnode.jsvariablesmoduleglobal-variables

提问by user779159

In one of my JS files I include another one. How can I set variables in the included module?

在我的一个 JS 文件中,我包含了另一个。如何在包含的模块中设置变量?

I thought doing something like this would work

我认为做这样的事情会奏效

var mymodule = require('mymodule.js');
mymodule.myvariable = 'test';

And then in mymodule

然后在我的模块中

this.myvariable === 'test';

But this doesn't work, it's undefined. What are the various options for passing a value into a module? I could just add the variable as a parameter to every function I call in mymodule, but that isn't ideal.

但这不起作用,它是undefined。将值传递给模块的各种选项是什么?我可以将变量作为参数添加到我在 mymodule 中调用的每个函数,但这并不理想。

Is there a way to do it without globals, so that I can set the variables independently in various required modules, like this?

有没有办法在没有全局变量的情况下做到这一点,这样我就可以在各种所需的模块中独立设置变量,像这样?

var mymodule1 = require('mymodule.js');
var mymodule2 = require('mymodule.js');
mymodule1.myvariable = 'test1';
mymodule2.myvariable = 'test2';

回答by Noman Ur Rehman

NodeJS require()will always load the module once so you will need to implement scoping into your module where different instances of the module can exist with their own internal state.

NodeJSrequire()将始终加载一次模块,因此您需要在模块中实现作用域,其中模块的不同实例可以以它们自己的内部状态存在。

You can implement your module as a JS class like:

您可以将模块实现为 JS 类,例如:

var MyModule = function(){};

MyModule.prototype.someFunction = function(params){
    this.someVar = params;
}

MyModule.prototype.anotherFunction = function(key, value){
    this[key] = value;
}

module.exports = MyModule;

Then in your code;

然后在你的代码中;

var MyModule = require('MyModule');

someModule = new MyModule();

// treat someModule like an object with its getters/setters/functions

回答by Adam Stone

The problem with what you were doing is that you set the variable after importing, but this.myvariable === 'test';was being called when the module was imported, before your variable was set.

您所做的问题是您在导入后设置了变量,但在导入this.myvariable === 'test';模块时在设置变量之前被调用。

You can have your module export a function and then call the function when you import, passing your variable as an argument.

您可以让您的模块导出一个函数,然后在导入时调用该函数,将您的变量作为参数传递。

module.exports = function(myVar) {
  var myModule = {
    // has access to myVar 
    ...
  };

  return myModule; 
};

When you import,

导入时,

var myModule = require('myModule')(myVar);

If you use this method, keep in mind that you get a different instance of your module wherever you import, which may not be what you want.

如果您使用此方法,请记住,无论您在何处导入,都会获得不同的模块实例,这可能不是您想要的。

If you want to set values of a module from outside the module, a good option is to have your module export an object with a setter method, and use that to set the value of the variable as a property of the object. This makes it more clear that you want this value to be settable, whereas just doing myModule.myVar =can set you up for confusion later.

如果您想从模块外部设置模块的值,一个不错的选择是让您的模块使用 setter 方法导出一个对象,并使用该方法将变量的值设置为对象的属性。这更清楚地表明您希望该值是可设置的,而只是这样做myModule.myVar =会使您以后感到困惑。

module.exports = {
  myVar: null,

  setMyVar: function(myVar) {
    this.myVar = myVar;
  },

  ...

};

In this case you're accessing the same instance of the model wherever you import it.

在这种情况下,无论您在何处导入模型,都将访问模型的相同实例。

Edit in response to comment

编辑以回应评论

In the first option you show where you get a different instance each time, how can I export multiple functions that each share the same myVar? If that module exports 5 functions each that need myVar, can I set it in one place like at import time rather than passing it into each function?

在第一个选项中,您显示每次获得不同实例的位置,如何导出每个共享相同 myVar 的多个函数?如果该模块导出 5 个函数,每个函数都需要 myVar,我可以在导入时将其设置在一个地方,而不是将其传递给每个函数吗?

Not entirely sure if I understand what you're describing, but you could do something like this:

不完全确定我是否理解你的描述,但你可以做这样的事情:

module.exports = function(myVar) {
  var modules = {};
  modules.someModule = {...};
  modules.anotherModule = {...};
  ...

  return modules;
};

Each of these sub-modules would have access to the same myVar. So you would import as above and the result would be an object containing each of your five modules as properties. I can't say whether this is a good idea, it's getting pretty convoluted, but maybe it makes sense for your situation.

这些子模块中的每一个都可以访问相同的 myVar。因此,您将按上述方式导入,结果将是一个对象,其中包含五个模块中的每一个作为属性。我不能说这是否是一个好主意,它变得非常复杂,但也许它对您的情况有意义。

回答by Wim Mostmans

Should work just fine. Here is a working example:

应该工作得很好。这是一个工作示例:

index.js

索引.js

var module = require('./module.js');
module.myvar = 'Hello world';
module.test();

module.js

模块.js

module.exports = {
    test: function() {
        console.log('var is', this.myvar);
    }
};

Keep in mind if you use thisin a closure that the scope isn't any longer the module itself. So that could be your problem.

请记住,如果您this在闭包中使用,范围不再是模块本身。所以这可能是你的问题。

Can you show me the part of the module code where you use this?

你能告诉我你使用它的模块代码部分吗?