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"
}
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);
});
});
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);
});
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.