Nodejs cannot find installed module on Windows
Nodejs cannot find installed module on Windows
问题
I am learning nodejs at the moment on Windows. Several modules are installed globally with npm.cmd, and nodejs failed to find the installed modules. Take jade for example,
npm install jade -g
Jade is installed in directory "C:\Program Files (x86)\nodejs\node_modules"
, but the following code will fail with a "Cannot find module 'jade'"
error,
var jade = require('jade');
However, the code will run successfully when jade is locally installed (without -g option in npm). I don't want to use locally-installed modules, it's a waste of disk space for me. How can I make the globally-installed modules work on Windows?
回答
Add an environment variable called NODE_PATH
and set it to %USERPROFILE%\Application Data\npm\node_modules
(Windows XP), %AppData%\npm\node_modules
(Windows 7/8/10), or wherever npm ends up installing the modules on your Windows flavor. To be done with it once and for all, add this as a System variable in the Advanced tab of the System Properties dialog (run control.exe sysdm.cpl,System,3
).
Quick solution in Windows 7+ is to just run:
rem for future
setx NODE_PATH %AppData%\npm\node_modules
rem for current session
set NODE_PATH=%AppData%\npm\node_modules
It's worth to mention that NODE_PATH
is only used when importing modules in Node apps. When you want to use globally installed modules' binaries in your CLI you need to add it also to your PATH
, but without node_modules
part (for example %AppData%\npm
in Windows 7/8/10).
Old story
I'm pretty much new to node.js myself so I can be not entirely right but from my experience it's works this way:
- -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).
See similar question for more details: How do I install a module globally using npm?
win10添加一个新的环境变量
NODE_PATH 对应的值是%AppData%\npm\node_modules
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2019-12-23 onedrive忽略子文件夹
2019-12-23 git filter-repo
2015-12-23 Hosting Your Own NuGet Feeds
2015-12-23 NuGet学习笔记
2015-12-23 软件版本的处理