从全局文件夹加载


【Loading from the global folders】

如果 NODE_PATH 环境变量被设置为由冒号分隔的绝对路径列表,那么如果模块在其他位置没有找到,Node.js 将在这些路径中搜索模块。

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

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

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

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

NODE_PATH 仍然受支持,但现在 Node.js 生态系统已经形成了定位依赖模块的约定,因此它的必要性较小。有时依赖于 NODE_PATH 的部署会表现出令人惊讶的行为,尤其是在用户不知道必须设置 NODE_PATH 时。有时模块的依赖发生变化,导致在搜索 NODE_PATH 时加载了不同的版本(甚至是不同的模块)。

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

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

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

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

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

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

【These are mostly for historic reasons.】

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

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