How to stop app that node.js express 'npm star

2019-01-21 07:14发布

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

> nodetest2@0.0.1 stop /home/nodetest2
> pkill -s SIGINT nodetest2

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

npm ERR! nodetest2@0.0.1 stop: `pkill -s SIGINT nodetest2`
npm ERR! Exit status 2

标签: node.js npm
9条回答
做个烂人
2楼-- · 2019-01-21 08:05

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.

查看更多
可以哭但决不认输i
3楼-- · 2019-01-21 08:05

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

查看更多
Animai°情兽
4楼-- · 2019-01-21 08:11

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.

查看更多
登录 后发表回答