Javascript node.js 全局变量?

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

node.js global variables?

javascriptnode.jsexpress

提问by Harry

I asked here: node.js require inheritance?

我在这里问: node.js 需要继承吗?

and was told that I can set variables to the global scope by leaving out the var.

并被告知我可以通过省略 var 将变量设置为全局范围。

This does not work for me.

这对我不起作用。

ie:

IE:

_ = require('underscore');

Does not make the _ available on required files. I can set with express's app.setand have it available elsewhere though.

不使 _ 可用于所需文件。我可以用快递设置,app.set但可以在其他地方使用。

Can somebody confirm that this is supposed to work? Thanks.

有人可以确认这应该有效吗?谢谢。

回答by masylum

You can use globallike so:

你可以global像这样使用:

global._ = require('underscore')

回答by Dave Dopson

In node, you can set global variables via the "global" or "GLOBAL" object:

在节点中,您可以通过“global”或“GLOBAL”对象设置全局变量:

GLOBAL._ = require('underscore'); // but you "shouldn't" do this! (see note below)

or more usefully...

或更有用...

GLOBAL.window = GLOBAL;  // like in the browser

From the node source, you can see that these are aliased to each other:

从节点源中,您可以看到这些是互为别名的:

node-v0.6.6/src/node.js:
28:     global = this;
128:    global.GLOBAL = global;

In the code above, "this" is the global context. With the commonJS module system (which node uses), the "this" object inside of a module (ie, "your code") is NOT the global context. For proof of this, see below where I spew the "this" object and then the giant "GLOBAL" object.

在上面的代码中,“this”是全局上下文。使用 commonJS 模块系统(哪个节点使用),模块内的“this”对象(即“你的代码”)不是全局上下文。为了证明这一点,请参见下面我喷出的“this”对象,然后是巨大的“GLOBAL”对象。

console.log("\nTHIS:");
console.log(this);
console.log("\nGLOBAL:");
console.log(global);

/* outputs ...

THIS:
{}

GLOBAL:
{ ArrayBuffer: [Function: ArrayBuffer],
  Int8Array: { [Function] BYTES_PER_ELEMENT: 1 },
  Uint8Array: { [Function] BYTES_PER_ELEMENT: 1 },
  Int16Array: { [Function] BYTES_PER_ELEMENT: 2 },
  Uint16Array: { [Function] BYTES_PER_ELEMENT: 2 },
  Int32Array: { [Function] BYTES_PER_ELEMENT: 4 },
  Uint32Array: { [Function] BYTES_PER_ELEMENT: 4 },
  Float32Array: { [Function] BYTES_PER_ELEMENT: 4 },
  Float64Array: { [Function] BYTES_PER_ELEMENT: 8 },
  DataView: [Function: DataView],
  global: [Circular],
  process: 
   { EventEmitter: [Function: EventEmitter],
     title: 'node',
     assert: [Function],
     version: 'v0.6.5',
     _tickCallback: [Function],
     moduleLoadList: 
      [ 'Binding evals',
        'Binding natives',
        'NativeModule events',
        'NativeModule buffer',
        'Binding buffer',
        'NativeModule assert',
        'NativeModule util',
        'NativeModule path',
        'NativeModule module',
        'NativeModule fs',
        'Binding fs',
        'Binding constants',
        'NativeModule stream',
        'NativeModule console',
        'Binding tty_wrap',
        'NativeModule tty',
        'NativeModule net',
        'NativeModule timers',
        'Binding timer_wrap',
        'NativeModule _linklist' ],
     versions: 
      { node: '0.6.5',
        v8: '3.6.6.11',
        ares: '1.7.5-DEV',
        uv: '0.6',
        openssl: '0.9.8n' },
     nextTick: [Function],
     stdout: [Getter],
     arch: 'x64',
     stderr: [Getter],
     platform: 'darwin',
     argv: [ 'node', '/workspace/zd/zgap/darwin-js/index.js' ],
     stdin: [Getter],
     env: 
      { TERM_PROGRAM: 'iTerm.app',
        'COM_GOOGLE_CHROME_FRAMEWORK_SERVICE_PROCESS/USERS/DDOPSON/LIBRARY/APPLICATION_SUPPORT/GOOGLE/CHROME_SOCKET': '/tmp/launch-nNl1vo/ServiceProcessSocket',
        TERM: 'xterm',
        SHELL: '/bin/bash',
        TMPDIR: '/var/folders/2h/2hQmtmXlFT4yVGtr5DBpdl9LAiQ/-Tmp-/',
        Apple_PubSub_Socket_Render: '/tmp/launch-9Ga0PT/Render',
        USER: 'ddopson',
        COMMAND_MODE: 'unix2003',
        SSH_AUTH_SOCK: '/tmp/launch-sD905b/Listeners',
        __CF_USER_TEXT_ENCODING: '0x12D732E7:0:0',
        PATH: '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:~/bin:/usr/X11/bin',
        PWD: '/workspace/zd/zgap/darwin-js',
        LANG: 'en_US.UTF-8',
        ITERM_PROFILE: 'Default',
        SHLVL: '1',
        COLORFGBG: '7;0',
        HOME: '/Users/ddopson',
        ITERM_SESSION_ID: 'w0t0p0',
        LOGNAME: 'ddopson',
        DISPLAY: '/tmp/launch-l9RQXI/org.x:0',
        OLDPWD: '/workspace/zd/zgap/darwin-js/external',
        _: './index.js' },
     openStdin: [Function],
     exit: [Function],
     pid: 10321,
     features: 
      { debug: false,
        uv: true,
        ipv6: true,
        tls_npn: false,
        tls_sni: true,
        tls: true },
     kill: [Function],
     execPath: '/usr/local/bin/node',
     addListener: [Function],
     _needTickCallback: [Function],
     on: [Function],
     removeListener: [Function],
     reallyExit: [Function],
     chdir: [Function],
     debug: [Function],
     error: [Function],
     cwd: [Function],
     watchFile: [Function],
     umask: [Function],
     getuid: [Function],
     unwatchFile: [Function],
     mixin: [Function],
     setuid: [Function],
     setgid: [Function],
     createChildProcess: [Function],
     getgid: [Function],
     inherits: [Function],
     _kill: [Function],
     _byteLength: [Function],
     mainModule: 
      { id: '.',
        exports: {},
        parent: null,
        filename: '/workspace/zd/zgap/darwin-js/index.js',
        loaded: false,
        exited: false,
        children: [],
        paths: [Object] },
     _debugProcess: [Function],
     dlopen: [Function],
     uptime: [Function],
     memoryUsage: [Function],
     uvCounters: [Function],
     binding: [Function] },
  GLOBAL: [Circular],
  root: [Circular],
  Buffer: 
   { [Function: Buffer]
     poolSize: 8192,
     isBuffer: [Function: isBuffer],
     byteLength: [Function],
     _charsWritten: 8 },
  setTimeout: [Function],
  setInterval: [Function],
  clearTimeout: [Function],
  clearInterval: [Function],
  console: [Getter],
  window: [Circular],
  navigator: {} }
*/

** Note: regarding setting "GLOBAL._", in general you should just do var _ = require('underscore');. Yes, you do that in every single file that uses underscore, just like how in Java you do import com.foo.bar;. This makes it easier to figure out what your code is doing because the linkages between files are 'explicit'. Mildly annoying, but a good thing. .... That's the preaching.

** 注意:关于设置“GLOBAL._”,一般你应该只做var _ = require('underscore');. 是的,您在每个使用下划线的文件中都这样做,就像在 Java 中一样import com.foo.bar;。由于文件之间的链接是“显式”的,因此可以更轻松地弄清楚您的代码在做什么。有点烦人,但这是一件好事。....这就是说教。

There is an exception to every rule. I have had precisely exactly ONE instance where I needed to set "GLOBAL._". I was creating a system for defining "config" files which were basically JSON, but were "written in JS" to allow a bit more flexibility. Such config files had no 'require' statements, but I wanted them to have access to underscore (the ENTIRE system was predicated on underscore and underscore templates), so before evaluating the "config", I would set "GLOBAL._". So yeah, for every rule, there's an exception somewhere. But you had better have a darn good reason and not just "i get tired of typing 'require' so I want to break with convention".

每条规则都有例外。我恰好有一个需要设置“GLOBAL._”的实例。我正在创建一个用于定义“配置”文件的系统,这些文件基本上是 JSON,但“用 JS 编写”以允许更大的灵活性。此类配置文件没有“要求”语句,但我希望它们能够访问下划线(整个系统基于下划线和下划线模板),因此在评估“配置”之前,我将设置“GLOBAL._”。所以是的,对于每个规则,某处都有一个例外。但是你最好有一个很好的理由,而不仅仅是“我厌倦了输入'require',所以我想打破常规”。

回答by Oliver Dixon

The other solutions that use the GLOBAL keyword are a nightmare to maintain/readability (+namespace pollution and bugs) when the project gets bigger. I've seen this mistake many times and had the hassle of fixing it.

当项目变大时,使用 GLOBAL 关键字的其他解决方案是维护/可读性(+命名空间污染和错误)的噩梦。我已经多次看到这个错误并且很难修复它。

Use a JS file then use module exports.

使用 JS 文件,然后使用模块导出。

Example:

例子:

globals.js

globals.js

var Globals = {
    'domain':'www.MrGlobal.com';
}

module.exports = Globals;

Then if you want to use these, use require.

然后,如果您想使用这些,请使用 require。

var globals = require('globals'); //<< globals.js path
globals.domain //<< Domain.

回答by Igor Parra

What about a global namespace like global.MYAPI = {}

像这样的全局命名空间怎么样 global.MYAPI = {}

global.MYAPI._ = require('underscore')


Edit after camilo-martin's comment: All other posters talk about the bad pattern involved. So leaving that discussion aside, the best way to have a variable defined globally (OP's question) is through namespaces.

在卡米洛马丁的评论后编辑:所有其他海报都在谈论所涉及的不良模式。因此,将讨论放在一边,全局定义变量的最佳方法(OP 的问题)是通过名称空间。

@tip: http://thanpol.as/javascript/development-using-namespaces

@提示:http://thanpol.as/javascript/development-using-namespaces

回答by Joao Falcao

You can just use the global object.

您可以只使用全局对象。

var X = ['a', 'b', 'c'];
global.x = X;

console.log(x);
//['a', 'b', 'c']

回答by DrunkenBeetle

I agree that using the global/GLOBAL namespace for setting anything global is bad practice and don't use it at all in theory (in theorybeing the operative word). However (yes, the operative) I do use it for setting custom Error classes:

我同意使用 global/GLOBAL 命名空间来设置任何全局变量是不好的做法,理论上根本不要使用它(理论上是操作词)。但是(是的,操作员)我确实使用它来设置自定义错误类:

// Some global/config file that gets called in initialisation

global.MyError = [Function of MyError];

Yes, taboo here, but if your site/project uses custom errors throughout the place, you would basically need to define it everywhere, or atleast somewhere to:

是的,这里是禁忌,但是如果您的站点/项目在整个地方使用自定义错误,您基本上需要在任何地方定义它,或者至少在某个地方:

  1. Define the Error class in the first place
  2. In the script where you're throwing it
  3. In the script where you're catching it
  1. 首先定义Error类
  2. 在你抛出它的脚本中
  3. 在您捕获它的脚本中

Defining my custom errors in the global namespace saves me the hassle of require'ing my customer error library. Imaging throwing a custom error where that custom error is undefined.

在全局命名空间中定义我的自定义错误可以省去要求我的客户错误库的麻烦。成像抛出自定义错误,其中自定义错误未定义。

Also too, if this is wrong then please let me know as I've only just started doing this recently

另外,如果这是错误的,请告诉我,因为我最近才刚刚开始这样做