Javascript 在 Node.js 中的文件之间共享变量?

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

Share variables between files in Node.js?

javascriptnode.jsglobal-variables

提问by never_had_a_name

Here are 2 files:

这里有2个文件:

// main.js
require('./modules');
console.log(name); // prints "foobar"

// module.js
name = "foobar";

When I don't have "var" it works. But when I have:

当我没有“var”时,它就起作用了。但是当我有:

// module.js
var name = "foobar";

name will be undefined in main.js.

name 在 main.js 中将是未定义的。

I have heard that global variables are bad and you better use "var" before the references. But is this a case where global variables are good?

我听说全局变量不好,你最好在引用之前使用“var”。但这是全局变量好的情况吗?

回答by jmar777

Global variables are almostnever a good thing (maybe an exception or two out there...). In this case, it looks like you really just want to export your "name" variable. E.g.,

全局变量几乎从来都不是一件好事(可能有一两个例外......)。在这种情况下,看起来您真的只想导出您的“名称”变量。例如,

// module.js
var name = "foobar";
// export it
exports.name = name;

Then, in main.js...

然后,在 main.js 中...

//main.js
// get a reference to your required module
var myModule = require('./module');

// name is a member of myModule due to the export above
var name = myModule.name;

回答by Felipe Pereira

I'm unable to find an scenario where a global varis the best option, of course you can have one, but take a look at these examples and you may find a better way to accomplish the same:

我找不到全局var是最佳选择的场景,当然你可以有一个,但看看这些例子,你可能会找到一个更好的方法来完成同样的事情:

Scenario 1: Put the stuff in config files

场景 1:把东西放在配置文件中

You need some value that it's the same across the application, but it changes depending on the environment (production, dev or test), the mailer type as example, you'd need:

您需要一些在整个应用程序中相同的值,但它会根据环境(生产、开发或测试)而变化,例如邮件程序类型,您需要:

// File: config/environments/production.json
{
    "mailerType": "SMTP",
    "mailerConfig": {
      "service": "Gmail",
      ....
}

and

// File: config/environments/test.json
{
    "mailerType": "Stub",
    "mailerConfig": {
      "error": false
    }
}

(make a similar config for dev too)

(也为 dev 做一个类似的配置)

To decide which config will be loaded make a main config file (this will be used all over the application)

要决定加载哪个配置,请制作一个主配置文件(这将在整个应用程序中使用)

// File: config/config.js
var _ = require('underscore');

module.exports = _.extend(
    require(__dirname + '/../config/environments/' + process.env.NODE_ENV + '.json') || {});

And now you can get the datalike this:

现在,你可以得到的数据是这样的:

// File: server.js
...
var config = require('./config/config');
...
mailer.setTransport(nodemailer.createTransport(config.mailerType, config.mailerConfig));

Scenario 2: Use a constants file

场景 2:使用常量文件

// File: constants.js
module.exports = {
  appName: 'My neat app',
  currentAPIVersion: 3
};

And use it this way

并以这种方式使用它

// File: config/routes.js

var constants = require('../constants');

module.exports = function(app, passport, auth) {
  var apiroot = '/api/v' + constants.currentAPIVersion;
...
  app.post(apiroot + '/users', users.create);
...

Scenario 3: Use a helper function to get/set the data

场景 3:使用辅助函数获取/设置数据

Not a big fan of this one, but at least you can track the use of the 'name' (citing the OP's example) and put validations in place.

不是这个的忠实粉丝,但至少您可以跟踪“名称”的使用(引用 OP 的示例)并进行验证。

// File: helpers/nameHelper.js

var _name = 'I shall not be null'

exports.getName = function() {
  return _name;
};

exports.setName = function(name) {
  //validate the name...
  _name = name;
};

And use it

并使用它

// File: controllers/users.js

var nameHelper = require('../helpers/nameHelper.js');

exports.create = function(req, res, next) {
  var user = new User();
  user.name = req.body.name || nameHelper.getName();
  ...

There could be a use case when there is no other solution than having a global var, but usually you can share the data in your app using one of these scenarios, if you are starting to use node.js (as I was sometime ago) try to organize the way you handle the data over there because it can get messy really quick.

可能有一个用例,除了拥有 global 之外没有其他解决方案var,但通常您可以使用这些场景之一在您的应用程序中共享数据,如果您开始使用 node.js(就像我之前那样)尝试组织你在那里处理数据的方式,因为它很快就会变得混乱。

回答by Vineeth Bhaskaran

If we need to share multiple variables use the below format

如果我们需要共享多个变量,请使用以下格式

//module.js
   let name='foobar';
   let city='xyz';
   let company='companyName';

   module.exports={
    name,
    city,
    company
  }

Usage

用法

  // main.js
    require('./modules');
    console.log(name); // print 'foobar'

回答by StefansArya

Save any variable that want to be shared as one object. Then pass it to loaded module so it could access the variable through object reference..

将要共享的任何变量保存为一个对象。然后将它传递给加载的模块,以便它可以通过对象引用访问变量..

// main.js
var myModule = require('./module.js');
var shares = {value:123};

// Initialize module and pass the shareable object
myModule.init(shares);

// The value was changed from init2 on the other file
console.log(shares.value); // 789

On the other file..

在另一个文件..

// module.js
var shared = null;

function init2(){
    console.log(shared.value); // 123
    shared.value = 789;
}

module.exports = {
    init:function(obj){
        // Save the shared object on current module
        shared = obj;

        // Call something outside
        init2();
    }
}

回答by criz

a variable declared with or without the var keyword got attached to the global object. This is the basis for creating global variables in Node by declaring variables without the var keyword. While variables declared with the var keyword remain local to a module.

使用或不使用 var 关键字声明的变量附加到全局对象。这是通过声明不带 var 关键字的变量在 Node 中创建全局变量的基础。虽然用 var 关键字声明的变量对模块来说仍然是本地的。

see this article for further understanding - https://www.hacksparrow.com/global-variables-in-node-js.html

请参阅本文以进一步了解 - https://www.hacksparrow.com/global-variables-in-node-js.html

回答by LCB

With a different opinion, I think the globalvariables might be the best choice if you are going to publish your code to npm, cuz you cannot be sure that all packages are using the same release of your code. So if you use a file for exporting a singletonobject, it will cause issues here.

持不同意见,我认为global如果您要将代码发布到npm,变量可能是最佳选择,因为您无法确定所有包都使用相同版本的代码。因此,如果您使用文件导出singleton对象,则会在此处引起问题。

You can choose global, require.mainor any other objects which are shared across files.

您可以选择globalrequire.main或跨文件共享的任何其他对象。

Please tell me if there are some better solutions.

请告诉我是否有更好的解决方案。