process.env


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

【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'
} 

可以修改这个对象,但这些修改不会在 Node.js 进程外生效,或者(除非明确请求)在其他 Worker 线程中生效。换句话说,以下示例将无法使用:

【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:】

import { env } from 'node:process';

env.foo = 'bar';
console.log(env.foo);const { env } = require('node:process');

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

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

【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.】

import { env } from 'node:process';

env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'const { env } = require('node:process');

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

使用 deleteprocess.env 中删除一个属性。

【Use delete to delete a property from process.env.】

import { env } from 'node:process';

env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefinedconst { env } = require('node:process');

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

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

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

import { env } from 'node:process';

env.TEST = 1;
console.log(env.test);
// => 1const { env } = require('node:process');

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

除非在创建 Worker 实例时明确指定,否则每个 Worker 线程都有自己的 process.env 副本,该副本基于其父线程的 process.env,或基于作为 Worker 构造函数的 env 选项指定的内容。对 process.env 的更改不会在 Worker 线程之间可见,只有主线程才能进行对操作系统或本地插件可见的更改。在 Windows 上,Worker 实例上的 process.env 副本以区分大小写的方式运行,这与主线程不同。

【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. On Windows, a copy of process.env on a Worker instance operates in a case-sensitive manner unlike the main thread.】