[node.js] How to stop app that node.js express 'npm start'

You build node.js app with express v4.x then start your app by npm start. My question is how to stop the app? Is there npm stop?

EDIT to include the error when implement npm stop

/home/nodetest2# npm stop

> [email protected] stop /home/nodetest2
> pkill -s SIGINT nodetest2

pkill: invalid argument for option 's' -- SIGINT

npm ERR! [email protected] stop: `pkill -s SIGINT nodetest2`
npm ERR! Exit status 2

This question is related to node.js npm

The answer is


For windows machine (I'm on windows 10), if CTRL + C (Cancel/Abort) Command on cli doesn't work, and the screen shows up like this:

enter image description here

Try to hit ENTER first (or any key would do) and then CTRL + C and the current process would ask if you want to terminate the batch job:

enter image description here

Perhaps CTRL+C only terminates the parent process while npm start runs with other child processes. Quite unsure why you have to hit that extra key though prior to CTRL+ C, but it works better than having to close the command line and start again.

A related issue you might want to check: https://github.com/mysticatea/npm-run-all/issues/74


You have to press combination ctrl + z My os is Ubuntu


You can use pm2

https://pm2.keymetrics.io/docs/usage/quick-start/

after installation just type in terminal

pm2 start app.js and then

pm2 stop 0 to stop your server


This is a mintty version problem alternatively use cmd. To kill server process just run this command:

    taskkill -F -IM node.exe

All the other solutions here are OS dependent. An independent solution for any OS uses socket.io as follows.

package.json has two scripts:

"scripts": {
  "start": "node server.js",
  "stop": "node server.stop.js"
}

server.js - Your usual express stuff lives here

const express = require('express');
const app = express();
const server = http.createServer(app);
server.listen(80, () => {
  console.log('HTTP server listening on port 80');
});

// Now for the socket.io stuff - NOTE THIS IS A RESTFUL HTTP SERVER
// We are only using socket.io here to respond to the npmStop signal
// To support IPC (Inter Process Communication) AKA RPC (Remote P.C.)

const io = require('socket.io')(server);
io.on('connection', (socketServer) => {
  socketServer.on('npmStop', () => {
    process.exit(0);
  });
});

server.stop.js

const io = require('socket.io-client');
const socketClient = io.connect('http://localhost'); // Specify port if your express server is not using default port 80

socketClient.on('connect', () => {
  socketClient.emit('npmStop');
  setTimeout(() => {
    process.exit(0);
  }, 1000);
});

Test it out

npm start (to start your server as usual)

npm stop (this will now stop your running server)

The above code has not been tested (it is a cut down version of my code, my code does work) but hopefully it works as is. Either way, it provides the general direction to take if you want to use socket.io to stop your server.


In case your json file does not have a script to stop the app, an option that I use is just by pressing ctrl+C on the cmd.


Here's another solution that mixes ideas from the previous answers. It takes the "kill process" approach while addressing the concern about platform independence.

It relies on the tree-kill package to handle killing the server process tree. I found killing the entire process tree necessary in my projects because some tools (e.g. babel-node) spawn child processes. If you only need to kill a single process, you can replace tree-kill with the built-in process.kill() method.

The solution follows (the first two arguments to spawn() should be modified to reflect the specific recipe for running your server):

build/start-server.js

import { spawn } from 'child_process'
import fs from 'fs'

const child = spawn('node', [
  'dist/server.js'
], {
  detached: true,
  stdio: 'ignore'
})
child.unref()

if (typeof child.pid !== 'undefined') {
  fs.writeFileSync('.server.pid', child.pid, {
    encoding: 'utf8'
  })
}

build/stop-server.js

import fs from 'fs'
import kill from 'tree-kill'

const serverPid = fs.readFileSync('.server.pid', {
  encoding: 'utf8'
})
fs.unlinkSync('.server.pid')

kill(serverPid)

package.json

"scripts": {
  "start": "babel-node build/start-server.js",
  "stop": "babel-node build/stop-server.js"
}

Note that this solution detaches the start script from the server (i.e. npm start will return immediately and not block until the server is stopped). If you prefer the traditional blocking behavior, simply remove the options.detached argument to spawn() and the call to child.unref().


If you've already tried ctrl + c and it still doesn't work, you might want to try this. This has worked for me.

  1. Run command-line as an Administrator. Then run the command below to find the processID (PID) you want to kill. Type your port number in <yourPortNumber>

    netstat -ano | findstr :<yourPortNumber>

enter image description here

  1. Then you execute this command after you have identified the PID.

    taskkill /PID <typeYourPIDhere> /F

enter image description here

Kudos to @mit $ingh from http://www.callstack.in/tech/blog/windows-kill-process-by-port-number-157


Check with netstat -nptl all processes

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      1736/mongod     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1594/sshd       
tcp6       0      0 :::3977                 :::*                    LISTEN      6231/nodejs     
tcp6       0      0 :::22                   :::*                    LISTEN      1594/sshd       
tcp6       0      0 :::3200                 :::*                    LISTEN      5535/nodejs 

And it simply kills the process by the PID reference.... In my case I want to stop the 6231/nodejs so I execute the following command:

kill -9 6231

All (3) solotion is :

1- ctlr + C

2- in json file wreite a script that stop

"scripts": { "stop": "killall -SIGINT this-name-can-be-as-long-as-it-needs-to-be" },

*than in command write // npm stop //

3- Restart the pc


kill $(lsof -t -i :PORT_TO_KILL)

simplified version. Simple copy paste with the port to kill ex.5000


If is very simple, just kill the process..

localmacpro$ ps
  PID TTY           TIME CMD
 5014 ttys000    0:00.05 -bash
 6906 ttys000    0:00.29 npm   
 6907 ttys000    0:06.39 node /Users/roger_macpro/my-project/node_modules/.bin/webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
 6706 ttys001    0:00.05 -bash
 7157 ttys002    0:00.29 -bash

localmacpro$ kill -9 6907 6906

On MAC OS X(/BSD): you can try to use the lsof (list open files) command

$ sudo lsof -nPi -sTCP:LISTEN

enter image description here

and so

$ kill -9 3320

For production environments you should use Forever.js

It's so util for start and stop node process, you can list apps running too.

https://github.com/foreverjs/forever


When I tried the suggested solution I realized that my app name was truncated. I read up on process.title in the nodejs documentation (https://nodejs.org/docs/latest/api/process.html#process_process_title) and it says

On Linux and OS X, it's limited to the size of the binary name plus the length of the command line arguments because it overwrites the argv memory.

My app does not use any arguments, so I can add this line of code to my app.js

process.title = process.argv[2];

and then add these few lines to my package.json file

  "scripts": {
    "start": "node app.js this-name-can-be-as-long-as-it-needs-to-be",
    "stop": "killall -SIGINT this-name-can-be-as-long-as-it-needs-to-be"
  },

to use really long process names. npm start and npm stop work, of course npm stop will always terminate all running processes, but that is ok for me.


Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to npm

What does 'x packages are looking for funding' mean when running `npm install`? error: This is probably not a problem with npm. There is likely additional logging output above Module not found: Error: Can't resolve 'core-js/es6' Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist` ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean` What exactly is the 'react-scripts start' command? On npm install: Unhandled rejection Error: EACCES: permission denied Difference between npx and npm?