Node.js全局安装模块后脚本运行提示MODULE_NOT_FOUND错误的问题咨询
Hey there, let's break down why you can require() your globally installed module in the Node.js CLI but hit a MODULE_NOT_FOUND error when running a script. Here are the most common causes and fixes:
1. Node.js Doesn’t Auto-Search Global Modules by Default
Node.js’s require() function looks for modules in this order:
- Core Node.js modules (like
fsorpath) - The current project’s
node_modulesfolder - Directories listed in the
NODE_PATHenvironment variable
Globally installed modules live in a separate directory (run npm root -g to find its exact path), which isn’t included in the default search list for standalone scripts. The Node CLI works because it runs in a different context, but your script doesn’t inherit that access automatically.
Fixes for This:
Option 1: Install Locally (Highly Recommended)
Globally installed modules are designed for command-line tools, not for being imported in project code. Local installation avoids environment-specific bugs and makes your project portable for other developers:npm install <module_name>Now you can
require('<module_name>')without extra configuration.Option 2: Add Global Path to NODE_PATH
If you must use the global module, tell Node where to find it by setting theNODE_PATHvariable:- First get your global module path:
npm root -g - Set
NODE_PATHtemporarily (for your current terminal session):- macOS/Linux:
export NODE_PATH=$(npm root -g) - Windows (Command Prompt):
set NODE_PATH=%AppData%\npm\node_modules - Windows (PowerShell):
$env:NODE_PATH = (npm root -g)
- macOS/Linux:
- To make this permanent, add the command to your shell’s config file (like
.bashrcor.zshrcon macOS/Linux) or set it as a system environment variable on Windows.
- First get your global module path:
2. Verify Exact Module Name Spelling
It’s easy to overlook, but make sure the name in require() matches the module’s exact package name. Some modules use different display names vs. their published package names (e.g., a CLI tool called "my-tool" might be published as "my-tool-cli"). Run npm list -g to confirm the exact name of your globally installed module.
3. Check for Node.js Version Mismatch
If the globally installed module requires a specific Node.js version, but the version you’re using to run your script is incompatible, it can trigger unexpected errors. Verify:
- Your current Node.js version:
node -v - The module’s required Node version (check the
enginesfield in the module’spackage.json, located in the global module directory)
4. Rule Out Permission Issues
If you installed the global module with sudo (on macOS/Linux), the module directory might have restricted permissions that block your script from accessing it. Check permissions with:
ls -la $(npm root -g)
If needed, fix the permissions (long-term, avoid using sudo for npm installs by setting up a local npm directory instead).
内容的提问来源于stack exchange,提问作者Winslow




