我现在正在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上工作?


当前回答

尝试添加/编辑环境变量,得出结论:

Edit/add User variables (of the upper box) instead of System variables (of the lower part); otherwise you have to "run as administrator" to get it work. Append ;%AppData%\npm to Path in order to use it as a command line tool (if supported, like jshint and grunt-cli). Create NODE_PATH and set it %AppData%\npm\node_modules in order to require('<pkg_name>') in scripts without install it in the project directory. (But npm link is suggested for this requirement if you're working on OS with mklink such as Vista and newer.)

测试环境:

赢7 (Ent。, 64位,SP1), Node.js 4.2.4, npm 2.14.12 win8.1 (Ent。, 64位),Node.js 0.10.30, npm 1.4.21

其他回答

简而言之,在你的应用目录中使用npm link jade。

我将引用这个节点的博客文章…

In general, the rule of thumb is: If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your project. If you’re installing something that you want to use in your shell, on the command line or something, install it globally, so that its binaries end up in your PATH environment variable. ... Of course, there are some cases where you want to do both. Coffee-script and Express both are good examples of apps that have a command line interface, as well as a library. In those cases, you can do one of the following: Install it in both places. Seriously, are you that short on disk space? It’s fine, really. They’re tiny JavaScript programs. Install it globally, and then npm link coffee-script or npm link express (if you’re on a platform that supports symbolic links.) Then you only need to update the global copy to update all the symlinks as well.

如果你使用的是Windows,它需要一些步骤, 1)创建一个名为package.json的文件

 {
  "name": "hello"
, "version": "0.0.1"
, "dependencies": {
    "express": "*"
  }
}

其中hello是包的名称,*表示依赖项的最新版本

2)代码到你的项目目录并运行以下命令

npm安装

它会安装依赖项

我无意中发现了这个问题,因为我想在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。

我在Windows 7上运行时遇到了这个问题

npm install -g gulp

以管理员身份登录,同时以普通用户身份登录。

解决方案:当以普通用户执行相同的安装时(而不是“以admin身份运行”cmd),一切正常。我猜这与默认的安装和搜索路径有关。