我现在正在Windows上学习nodejs。有几个模块是通过npm全局安装的。nodejs无法找到已安装的模块。以玉为例,

npm install jade -g

Jade安装在“C:\Program Files (x86)\nodejs\node_modules”目录下,但下面的代码将失败,并提示“无法找到模块' Jade '”错误。

var jade = require('jade');

然而,当jade在本地安装时(npm中没有-g选项),代码将成功运行。我不想使用本地安装的模块,这对我来说是浪费磁盘空间。如何使全局安装的模块在Windows上工作?


当前回答

我知道我可以唤醒一个僵尸,但我认为这仍然是一个问题,如果你需要全局访问Windows 7上的节点模块,你需要将这个添加到你的全局变量路径:

C:\Users\{USER}\AppData\Roaming\npm

重要的是:只有这个没有node_modules部分,我花了半个小时才看到这个。

其他回答

我必须添加以下路径变量下的系统变量。在用户变量下设置变量不适合我。我用的是windows 11。

%USERPROFILE%\AppData\Roaming\npm

添加一个名为NODE_PATH的环境变量,并将其设置为%USERPROFILE%\Application Data\npm\node_modules (Windows XP), %AppData%\npm\node_modules (Windows 7/8/10),或者npm最终在Windows版本上安装模块的任何地方。为了一劳永逸地完成它,在系统属性对话框的高级选项卡中添加这个系统变量(运行control.exe sysdm.cpl,System,3)。

Windows 7+的快速解决方案是运行:

rem for future
setx NODE_PATH %AppData%\npm\node_modules
rem for current session
set NODE_PATH=%AppData%\npm\node_modules

值得一提的是,NODE_PATH只在导入Node应用中的模块时使用。当你想在你的CLI中使用全局安装模块的二进制文件时,你需要将它也添加到你的PATH中,但不需要node_modules部分(例如Windows 7/8/10中的%AppData%\npm)。


古老的故事

我自己对node.js很陌生,所以我可能不完全正确,但从我的经验来看,它是这样工作的:

-g is not a way to install global libraries, it's only a way to place them on system path so you can call them from command line without writing the full path to them. It is useful, for example, then node app is converting local files, like less — if you install it globally you can use it in any directory. node.js itself didn't look at the npm global dir, it is using another algorithm to find required files: http://nodejs.org/api/modules.html#modules_file_modules (basically its scanning every folder in the path, starting from the current for node_modules folder and checks it).

更多细节请参见类似的问题:如何使用npm全局安装一个模块?

我花了一段时间让全局模块工作。最后,我显式地将C:\Users\yourusername\AppData\Roaming\npm添加到“系统变量”下的PATH变量中。我还需要将这个变量放在列表中的nodejs path变量之前。

我用的是Windows 10。

对于windows,每个人都说你应该为nodejs和npm模块设置环境变量,但你知道为什么吗? 对于一些模块,他们有命令行工具,安装模块后,有[模块]。cmd文件在C:\Program Files\ nodejs中,用于在窗口命令中启动。因此,如果您没有将包含cmd文件的路径添加到环境变量% path %,则无法通过命令窗口成功启动它们。

我无意中发现了这个问题,因为我想在windows 10的新电脑上使用node.js和visual studio 2015。我在windows 7、8和8.1上使用node.js,从来没有问题node.js找到一个模块。我使用一个遗留的node.js 0.10.39,因为我必须使用这个版本,因为串行和RFXCOM模块。

windows 10的答案是在环境变量中使用C:\Users\User\node_modules设置NODE_PATH。