process.env


process.env 属性会返回包含用户环境的对象。 参见 environ(7)

此对象的示例如下所示:

{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'nodejscn',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/nodejscn',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/nodejscn',
  LOGNAME: 'nodejscn',
  _: '/usr/local/bin/node'
}

可以修改此对象,但这些修改不会反映到 Node.js 进程之外,或者(除非明确地要求)反映到其他 Worker 线程。 换句话说,以下示例不会起作用:

$ node -e 'process.env.foo = "bar"' && echo $foo

以下示例则会起作用:

process.env.foo = 'bar';
console.log(process.env.foo);

process.env 上为属性赋值会隐式地将值转换为字符串。 不推荐使用此行为。 当值不是字符串、数字或布尔值时,Node.js 未来的版本可能会抛出错误。

process.env.test = null;
console.log(process.env.test);
// => 'null'
process.env.test = undefined;
console.log(process.env.test);
// => 'undefined'

使用 delete 可以从 process.env 中删除属性。

process.env.TEST = 1;
delete process.env.TEST;
console.log(process.env.TEST);
// => undefined

在 Windows 操作系统上,环境变量不区分大小写。

process.env.TEST = 1;
console.log(process.env.test);
// => 1

除非在创建 Worker 实例时显式地指定,否则每个 Worker 线程都有自己的 process.env 副本(基于其父线程的 process.env,或者指定为 Worker 构造函数的 env 选项的任何内容)。 对于 process.env 的更改在 Worker 线程中是不可见的,并且只有主线程可以做出对操作系统或原生插件可见的更改。

The process.env property returns an object containing the user environment. See environ(7).

An example of this object looks like:

{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'maciej',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/maciej',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
  _: '/usr/local/bin/node'
}

It is possible to modify this object, but such modifications will not be reflected outside the Node.js process, or (unless explicitly requested) to other Worker threads. In other words, the following example would not work:

$ node -e 'process.env.foo = "bar"' && echo $foo

While the following will:

process.env.foo = 'bar';
console.log(process.env.foo);

Assigning a property on process.env will implicitly convert the value to a string. This behavior is deprecated. Future versions of Node.js may throw an error when the value is not a string, number, or boolean.

process.env.test = null;
console.log(process.env.test);
// => 'null'
process.env.test = undefined;
console.log(process.env.test);
// => 'undefined'

Use delete to delete a property from process.env.

process.env.TEST = 1;
delete process.env.TEST;
console.log(process.env.TEST);
// => undefined

On Windows operating systems, environment variables are case-insensitive.

process.env.TEST = 1;
console.log(process.env.test);
// => 1

Unless explicitly specified when creating a Worker instance, each Worker thread has its own copy of process.env, based on its parent thread’s process.env, or whatever was specified as the env option to the Worker constructor. Changes to process.env will not be visible across Worker threads, and only the main thread can make changes that are visible to the operating system or to native add-ons.