如何在 node.js 中使用全局变量?

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

How to use global variable in node.js?

node.js

提问by Bdfy

For example I want to use custom logger:

例如我想使用自定义记录器:

logger = require('basic-logger'),
logger.setLevel('info')

var customConfig = {
showMillis: true,
showTimestamp: true
}

var log = new logger(customConfig)

How to use this logger in other modules instead of console.log ?

如何在其他模块而不是 console.log 中使用这个记录器?

回答by Pickels

Most people advise against using global variables. If you want the same logger class in different modules you can do this

大多数人建议不要使用全局变量。如果你想在不同的模块中使用相同的记录器类,你可以这样做

logger.js

记录器.js

  module.exports = new logger(customConfig);

foobar.js

foob​​ar.js

  var logger = require('./logger');
  logger('barfoo');

If you do want a global variable you can do:

如果你确实想要一个全局变量,你可以这样做:

global.logger = new logger(customConfig);

回答by Sean H. Worthington

global.myNumber; //Delclaration of the global variable - undefined
global.myNumber = 5; //Global variable initialized to value 5. 
var myNumberSquared = global.myNumber * global.myNumber; //Using the global variable. 

Node.js is different from client Side JavaScript when it comes to global variables. Just because you use the word var at the top of your Node.js script does not mean the variable will be accessible by all objects you require such as your 'basic-logger' .

在全局变量方面,Node.js 与客户端 JavaScript 不同。仅仅因为您在 Node.js 脚本的顶部使用 var 一词并不意味着您需要的所有对象都可以访问该变量,例如您的 'basic-logger' 。

To make something global just put the word global and a dot in front of the variable's name. So if I want company_id to be global I call it global.company_id. But be careful, global.company_id and company_id are the same thing so don't name global variable the same thing as any other variable in any other script - any other script that will be running on your server or any other place within the same code.

要使某些内容成为全局变量,只需在变量名称前加上 global 一词和一个点即可。因此,如果我希望 company_id 是全球性的,我将其称为 global.company_id。但要小心, global.company_id 和 company_id 是一回事,所以不要将全局变量命名为与任何其他脚本中的任何其他变量相同的事物 - 将在您的服务器上或同一代码中的任何其他地方运行的任何其他脚本.

回答by Shubham Gautam

you can define it with using global or GLOBAL, nodejs supports both.

您可以使用 global 或 GLOBAL 来定义它,nodejs 两者都支持。

for e.g

例如

global.underscore = require("underscore");

or

或者

GLOBAL.underscore = require("underscore");

回答by Doron Segal

I would suggest everytime when using global check if the variable is already define by simply check

我建议每次使用全局检查时,如果变量已经通过简单检查定义

if (!global.logger){
  global.logger = require('my_logger');
}

I've found it to have better performance

我发现它有更好的性能

回答by Sushant Agrawal

May be following is better to avoid the ifstatement:

可能最好避免以下if语句:

global.logger || (global.logger = require('my_logger'));

回答by Raz

Global variables can be used in Node when used wisely.

明智地使用全局变量可以在 Node 中使用

Declaration of global variables in Node:

Node中全局变量的声明:

a = 10;
GLOBAL.a = 10;
global.a = 10;

All of the above commands the same actions with different syntaxes.

以上所有命令都使用不同的语法执行相同的操作。

Use global variables when they are not about to be changed

在不打算更改时使用全局变量

Here an example of something that can happen when using global variables:

这是使用全局变量时可能发生的事情的示例:

// app.js
a = 10; // no var or let or const means global

// users.js
app.get("/users", (req, res, next) => {
   res.send(a); // 10;
});

// permissions.js
app.get("/permissions", (req, res, next) => {
   a = 11; // notice that there is no previous declaration of a in the permissions.js, means we looking for the global instance of a.
   res.send(a); // 11;
});

Explained:

解释:

Run users route first and receive 10;

先运行用户路由,收到10条;

Then run permissions route and receive 11;

然后运行权限路由,得到11;

Then run again the users route and receive 11 as well instead of 10;

然后再次运行用户路由并接收 11 而不是 10;

Global variables can be overtaken!

全局变量可以被超越!

Now think about using express and assignin res object as global.. And you end up with async error become corrupt and server is shuts down.

现在考虑使用 express 和 assignin res 对象作为全局对象..你最终会遇到异步错误变得损坏并且服务器关闭。

When to use global vars?

何时使用全局变量?

As I said - when var is not about to be changed. Anyways it's more recommended that you will be using the process.envobject from the config file.

正如我所说 - 当 var 不会改变时。无论如何,更建议您使用process.env配置文件中的对象。

回答by Kazuya Gosho

If your app is written in TypeScript, try

如果您的应用程序是用 TypeScript 编写的,请尝试

(global as any).logger = // ...

or

或者

Object.assign(global, { logger: // ... })

However, I will do it only when React Native's __DEV__in testing environment.

但是,我只会__DEV__在测试环境中使用React Native 时才这样做。