这里有2个文件:
// main.js
require('./modules');
console.log(name); // prints "foobar"
// module.js
name = "foobar";
当我没有“var”时,它就起作用了。但是当我有:
// module.js
var name = "foobar";
name 在 main.js 中将是未定义的。
我听说全局变量不好,你最好在引用之前使用“var”。但这是全局变量好的情况吗?
这里有2个文件:
// main.js
require('./modules');
console.log(name); // prints "foobar"
// module.js
name = "foobar";
当我没有“var”时,它就起作用了。但是当我有:
// module.js
var name = "foobar";
name 在 main.js 中将是未定义的。
我听说全局变量不好,你最好在引用之前使用“var”。但这是全局变量好的情况吗?
全局变量几乎从来都不是一件好事(可能有一两个例外......)。在这种情况下,看起来您真的只想导出“名称”变量。例如,
// module.js
var name = "foobar";
// export it
exports.name = name;
然后,在 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;
我找不到全局var是最佳选择的场景,当然你可以有一个,但看看这些例子,你可能会找到一个更好的方法来完成同样的事情:
您需要一些在整个应用程序中相同的值,但它会根据环境(生产、开发或测试)而变化,例如邮件程序类型,您需要:
// File: config/environments/production.json
{
    "mailerType": "SMTP",
    "mailerConfig": {
      "service": "Gmail",
      ....
}
和
// File: config/environments/test.json
{
    "mailerType": "Stub",
    "mailerConfig": {
      "error": false
    }
}
(也为 dev 做一个类似的配置)
要决定加载哪个配置,请制作一个主配置文件(这将在整个应用程序中使用)
// File: config/config.js
var _ = require('underscore');
module.exports = _.extend(
    require(__dirname + '/../config/environments/' + process.env.NODE_ENV + '.json') || {});
而现在,你可以得到的数据是这样的:
// File: server.js
...
var config = require('./config/config');
...
mailer.setTransport(nodemailer.createTransport(config.mailerType, config.mailerConfig));
// File: constants.js
module.exports = {
  appName: 'My neat app',
  currentAPIVersion: 3
};
并以这种方式使用它
// 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);
...
不是这个的忠实粉丝,但至少您可以跟踪“名称”的使用(引用 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;
};
并使用它
// 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();
  ...
可能有一个用例,除了拥有 global 之外没有其他解决方案var,但通常您可以使用这些场景之一在您的应用程序中共享数据,如果您开始使用 node.js(就像我以前一样)尝试组织你在那里处理数据的方式,因为它很快就会变得混乱。
如果我们需要共享多个变量,请使用以下格式
//module.js
   let name='foobar';
   let city='xyz';
   let company='companyName';
   module.exports={
    name,
    city,
    company
  }
用法
  // main.js
    require('./modules');
    console.log(name); // print 'foobar'
将要共享的任何变量保存为一个对象。然后将它传递给加载的module,以便它可以通过对象引用访问变量..
// 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
在另一个文件上..
// 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();
    }
}
使用或不使用 var 关键字声明的变量附加到全局对象。这是通过声明不带 var 关键字的变量在 Node 中创建全局变量的基础。虽然用 var 关键字声明的变量对module来说仍然是本地的。
请参阅本文以进一步了解 - https://www.hacksparrow.com/global-variables-in-node-js.html