chefcurry7 chefcurry7 - 1 year ago 134
Node.js Question

Npm script that finds and kills port that's in use

I'm on a windows machine and every time I quit a node process, and try to restart again I get a

Error: listen EADDRINUSE :::8004

I then have to do

netstat -o -n -a | findstr 0.0:8004
taskkill /F /PID <PID>

How can I write a script that finds and kills the PID by just doing
npm kill

Answer Source

1) the problem isn't about killing the server, it's about closing the port properly upon exiting. The program is obviously missing a server.close() in a process.on('exit', ..) and process.on('uncaughtException', ..).

2) the first argument allowed next to npm is one of a predefined set. Read the output of npm about that.

3) to answer you question, and do the lazy work, you can put the two commands inside a batch file, set the listening port as a parameter and declare a script section in package.json,

  "name": "myserver",
  "scripts": {
    "kill": "killserver.bat"

then use npm run kill -- 8004, The port number being of course a parameter in the batch. Note that this is longer and more complicated than simply calling the batch directly. see, it's useful to understand the possibilities offered by npm.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download