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

2019-01-21 08:03发布

问题:

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

回答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.



回答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.



回答3:

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.



回答4:

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


回答5:

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().



回答6:

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


回答7:

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

    taskkill -F -IM node.exe


回答8:

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

$ sudo lsof -nPi -sTCP:LISTEN

and so

$ kill -9 3320


回答9:

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



标签: node.js npm