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

Solution 1:

Yes, npm provides for a stop script too:

npm help npm-scripts

prestop, stop, poststop: Run by the npm stop command.

Set one of the above in your package.json, and then use npm stop

npm help npm-stop

You can make this really simple if you set in app.js,

process.title = myApp;

And, then in scripts.json,

"scripts": {
    "start": "app.js"
    , "stop": "pkill --signal SIGINT myApp"
}

That said, if this was me, I'd be using pm2 or something the automatically handled this on the basis of a git push.

Solution 2:

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.