从全局目录加载


如果 NODE_PATH 环境变量设置为以冒号分隔的绝对路径列表,则 Node.js 将在这些路径中搜索模块(如果它们在其他地方找不到)。

在 Windows 上,NODE_PATH 由分号 (;) 而不是冒号分隔。

在定义当前的模块解析算法之前,NODE_PATH 最初是为了支持从不同路径加载模块而创建的。

NODE_PATH 仍然受支持,但现在 Node.js 生态系统已经确定了用于定位依赖模块的约定,因此不太必要。 有时,当不知道必须设置 NODE_PATH 时,依赖 NODE_PATH 的部署会表现出意外的行为。 有时,模块的依赖项会发生变化,导致在搜索 NODE_PATH 时加载不同的版本(甚至不同的模块)。

此外,Node.js 将在以下 GLOBAL_FOLDERS 列表中搜索:

  • 1: $HOME/.node_modules
  • 2: $HOME/.node_libraries
  • 3: $PREFIX/lib/node

其中 $HOME 是用户的主目录,$PREFIX 是 Node.js 配置的 node_prefix

这些主要是出于历史原因。

强烈建议将依赖项放在本地 node_modules 文件夹中。 这些将加载得更快,更可靠。

If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then Node.js will search those paths for modules if they are not found elsewhere.

On Windows, NODE_PATH is delimited by semicolons (;) instead of colons.

NODE_PATH was originally created to support loading modules from varying paths before the current module resolution algorithm was defined.

NODE_PATH is still supported, but is less necessary now that the Node.js ecosystem has settled on a convention for locating dependent modules. Sometimes deployments that rely on NODE_PATH show surprising behavior when people are unaware that NODE_PATH must be set. Sometimes a module's dependencies change, causing a different version (or even a different module) to be loaded as the NODE_PATH is searched.

Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:

  • 1: $HOME/.node_modules
  • 2: $HOME/.node_libraries
  • 3: $PREFIX/lib/node

Where $HOME is the user's home directory, and $PREFIX is the Node.js configured node_prefix.

These are mostly for historic reasons.

It is strongly encouraged to place dependencies in the local node_modules folder. These will be loaded faster, and more reliably.