Windows下npm start启动多Node进程,代码修改不生效如何解决?
Hey there, I feel your pain—manually killing Node processes every time you change code is such a frustrating waste of time. Let’s get this sorted out with a couple of straightforward, developer-friendly solutions:
1. Use nodemon (The Go-To Dev Tool for This)
This is the industry standard for auto-reloading Node apps during development, and it handles process termination/restarts automatically so you don’t have to.
- First, install it as a dev dependency:
npm install --save-dev nodemon - Update your
package.jsonscripts to replace plainnodewith nodemon:"scripts": { "start": "nodemon ./your-entry-file.js", // Replace with your actual entry file path "start:prod": "node ./your-entry-file.js" // Keep a production-ready script if needed } - Now when you run
npm start, nodemon will watch your project files for changes. As soon as you save a modification, it’ll kill the old Node process and spin up a new one with your updated code—no manual process hunting required.
2. Use Node.js Built-in --watch (No Extra Packages Needed)
If you’re running Node.js 18 or later, you don’t even need external tools. Node has a native file-watching flag that does the job:
- Update your
package.jsonscripts like this:"scripts": { "start": "node --watch ./your-entry-file.js" } - Just like nodemon, this will auto-restart your app whenever files change, and it ensures only one process runs at a time. Perfect for simple projects where you don’t want extra dependencies.
3. Fix Underlying Process Leaks
If you’re still seeing stray Node processes hanging around, it’s likely because your app isn’t handling termination signals properly (like when you hit Ctrl+C). Add this snippet to your entry file to ensure graceful shutdown:
// Listen for interrupt signal (Ctrl+C) to clean up properly process.on('SIGINT', () => { console.log('Shutting down app gracefully...'); // Add cleanup tasks here: close database connections, stop servers, etc. process.exit(0); });
This ensures when you terminate the app, all background processes and open connections get closed properly, so no zombie processes stick around to cause duplicates later.
Also, double-check your original npm start script—make sure you aren’t using a background operator like & at the end (e.g., node app.js &). That sends the process to the background, making Ctrl+C not kill it, leading to duplicate processes piling up over time.
内容的提问来源于stack exchange,提问作者Ralph Marvin Addo

