使用WinSCP、Nginx及PM2部署应用时遭遇Require Stack错误的技术求助
Hey there, let's break down this error and walk through how to fix it! That MODULE_NOT_FOUND message means Node.js can't find a module you're trying to import in your server.js file, specifically on line 8 (as the require stack clearly points out). Here's a step-by-step troubleshooting plan:
1. First, pinpoint the problematic require statement
Open your server.js file and jump straight to line 8. Check exactly which module you're trying to import—it'll look like one of these two types:
- A third-party npm package:
require('express') - A local file/module:
require('./routes/api.js')orrequire('../config/db.js')
2. Troubleshoot based on module type
Case 1: Third-party npm module
- Verify the module is installed in your project's
node_modulesfolder. SSH into your server, navigate to your project root directory (cd /home/****/), and run:
If it doesn't show up in the list, install it directly on the server:npm list <module-name>
Pro tip: If you uploadednpm install <module-name>node_modulesvia WinSCP, there's a chance some hidden files or symlinks were skipped. Installing dependencies directly on the server is usually more reliable than uploading the folder.
Case 2: Local file/module
- Double-check the path: Node.js resolves relative paths from the directory where
server.jslives. Make sure the file you're trying to import exists at the exact path you specified. - Watch for Linux case sensitivity: Unlike Windows, Linux treats
Utils.jsandutils.jsas totally different files. Confirm your filename casing matches exactly what's in yourrequirestatement. - Verify the file exists on the server: Use SSH to run
ls /home/****/path-to-your-fileto confirm the file is where you expect it to be.
3. Check PM2's working directory
Sometimes PM2 runs your app from a different directory than your project root, which breaks relative path imports. To check the current working directory:
pm2 show server
Look for the cwd field. If it's not your project root, restart PM2 with the correct directory:
pm2 restart server --cwd /home/****/
4. Verify file permissions
Even if the file exists, Node.js might not have permission to read it. Check the file's permissions with:
ls -l /home/****/path-to-your-module-file
If needed, grant read permissions to the file:
chmod +r /home/****/path-to-your-module-file
Quick extra test
Try running your app directly with Node.js (not via PM2) to see if you get more detailed error output:
cd /home/****/ node server.js
This might spell out exactly which module is missing, making the fix even clearer.
内容的提问来源于stack exchange,提问作者tim

