如何停止 node.js 表达“npm start”的应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23258421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:12:09  来源:igfitidea点击:

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

node.jsnpm

提问by ngungo

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?

您使用 express v4.x 构建 node.js 应用程序,然后通过npm start启动您的应用程序。我的问题是如何停止应用程序?有npm stop吗?

EDITto include the error when implement npm stop

编辑以在实现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

采纳答案by Evan Carroll

Yes, npm provides for a stop script too:

是的,npm 也提供了一个停止脚本:

npm help npm-scripts

npm help npm-scripts

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

prestop、stop、poststop:通过 npm stop 命令运行。

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

在 package.json 中设置上述之一,然后使用 npm stop

npm help npm-stop

npm help npm-stop

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

如果你设置app.js,你可以让这变得非常简单,

process.title= myApp;

process.title= myApp;

And, then in scripts.json,

然后在scripts.json中,

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

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

也就是说,如果这是我,我会使用pm2或在 git push 的基础上自动处理的东西。

回答by danday74

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

这里的所有其他解决方案都依赖于操作系统。任何操作系统的独立解决方案使用 socket.io 如下。

package.jsonhas two scripts:

package.json有两个脚本:

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

server.js - Your usual express stuff lives here

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

server.stop.js

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 start(像往常一样启动你的服务器)

npm stop(this will now stop your running server)

npm stop(这将停止您正在运行的服务器)

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.

上面的代码尚未经过测试(它是我的代码的简化版本,我的代码确实可以工作)但希望它可以按原样工作。无论哪种方式,如果您想使用 socket.io 停止服务器,它都提供了一般的方向。

回答by danday74

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

当我尝试建议的解决方案时,我意识到我的应用程序名称被截断了。我阅读了process.titlenodejs 文档(https://nodejs.org/docs/latest/api/process.html#process_process_title),它说

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.

在 Linux 和 OS X 上,它仅限于二进制名称的大小加上命令行参数的长度,因为它会覆盖 argv 内存。

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

我的应用程序不使用任何参数,因此我可以将这行代码添加到我的 app.js

process.title = process.argv[2];

and then add these few lines to my package.jsonfile

然后将这几行添加到我的package.json文件中

  "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 startand npm stopwork, of course npm stopwill always terminate all running processes, but that is ok for me.

使用非常长的进程名称。 npm startnpm stop工作,当然npm stop总是会终止所有正在运行的进程,但这对我来说没问题。

回答by overcomer

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

在 MAC OS X(/BSD) 上:您可以尝试使用 lsof(列出打开的文件)命令

$ sudo lsof -nPi -sTCP:LISTEN

enter image description here

在此处输入图片说明

and so

所以

$ kill -9 3320

回答by Karan

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

这是一个薄荷版本问题,或者使用 cmd。要终止服务器进程,只需运行以下命令:

    taskkill -F -IM node.exe

回答by Samuel Ivan

Check with netstat -nptlall processes

使用netstat -nptl检查所有进程

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:

它只是通过 PID 引用终止进程......在我的情况下,我想停止 6231/nodejs 所以我执行以下命令:

kill -9 6231

回答by Rusty Shackleford

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-killpackage 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.

它依赖于tree-kill包来处理杀死服务器进程树。我发现在我的项目中必须杀死整个进程树,因为某些工具(例如babel-node)会产生子进程。如果只需要杀死单个进程,可以用内置process.kill()方法替换tree-kill 。

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

解决方案如下(spawn()应修改 to的前两个参数以反映运行服务器的特定方法):

build/start-server.js

构建/启动-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

构建/停止-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

包.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 startwill return immediately and not block until the server is stopped). If you prefer the traditional blocking behavior, simply remove the options.detachedargument to spawn()and the call to child.unref().

请注意,此解决方案将启动脚本与服务器分离(npm start即将立即返回并且不会阻塞直到服务器停止)。如果您更喜欢传统的阻塞行为,只需删除对 的options.detached参数spawn()和对 的调用child.unref()

回答by rogersfo

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

回答by Jamezuh

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

如果您已经尝试过ctrl + c但它仍然不起作用,您可能想尝试一下。这对我有用。

  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>

  1. 以管理员身份运行命令行。然后运行下面的命令来查找要杀死的进程ID(PID)。输入您的端口号<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

  1. 然后在确定 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

感谢来自http://www.callstack.in/tech/blog/windows-kill-process-by-port-number-157 的@mit $ingh

回答by Vincent Edward Gedaria Binua

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:

对于 Windows 机器(我使用的是 Windows 10),如果 cli 上的 CTRL + C(取消/中止)命令不起作用,并且屏幕显示如下:

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 (或任何键都可以),然后按 CTRL + C,当前进程会询问您是否要终止批处理作业:

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.

也许 CTRL+C 仅终止父进程,而 npm start 与其他子进程一起运行。很不确定为什么你必须在 CTRL+ C 之前按下那个额外的键,但它比关闭命令行并重新开始更有效。

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

您可能想要检查的相关问题:https: //github.com/mysticatea/npm-run-all/issues/74