繁体   English   中英

Node.js 全局变量

[英]Node.js global variables

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

有人告诉我,我可以通过省略变量来将变量设置为全局范围。

这对我不起作用。

也就是说,以下内容不会使_在所需文件上可用。

_ = require('underscore');

我可以使用 Express.js 的app.set进行设置,但可以在其他地方使用它。

这是应该的工作方式吗?

您可以像这样使用global

global._ = require('underscore')

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

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

或更有用...

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

从 Node.js 源代码中,您可以看到它们互为别名:

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

在上面的代码中,“this”是全局上下文。 使用CommonJS模块系统(Node.js 使用的),模块内的“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: {} }
*/

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

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

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

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

例子:

文件globals.js

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

module.exports = Globals;

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

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

使用像global.MYAPI = {}这样的全局命名空间:

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

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

提示: 使用命名空间进行开发

您可以只使用全局对象。

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

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

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

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

global.MyError = [Function of MyError];

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

  1. 首先定义Error类
  2. 在你抛出它的脚本中
  3. 在您捕获它的脚本中

在全局命名空间中定义我的自定义错误让我省去了require 'ing 我的客户错误库的麻烦。 成像抛出自定义错误,其中自定义错误未定义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM