简体   繁体   English

如何从 npm 脚本优雅地停止 NodeJS 进程

[英]How to Stop NodeJS process gracefully from npm script

I've a scenario to run cypress E2E test and for which , I need NodeJS application to be up.我有一个运行cypress E2E测试的场景,为此,我需要启动NodeJS应用程序。 So, I'm using wait-on library and i'm able to run the cypress E2E test but it leaves my NodeJS application running in background.因此,我正在使用wait-on库,并且能够运行cypress E2E测试,但它使我的NodeJS应用程序在后台运行。

I want to end the NodeJS process running in background as part of my cypress:e2e npm script.我想结束在后台运行的NodeJS进程作为我的cypress:e2e npm 脚本的一部分。


Question : How can I send SIGINT signal from npm script because in my server.ts , I'm exiting the process with SIGINT .问题:如何从 npm 脚本发送SIGINT信号,因为在我的server.ts 中,我正在使用SIGINT退出进程。 (no ctrl+c would help) (没有 ctrl+c 会有所帮助)


server.ts :服务器.ts:

/****************************/
/* Start Up The Node Server */
/****************************/
APP.listen(PORT, () => {
  logger.info(
    `Node application has started their node server on port ${PORT}`,
  )
})

process.on('SIGINT', () => process.exit(1))

npm scripts: npm 脚本:

{
    "start": "node dist/server",
    "test:e2e": "ng e2e",
    "stop": ""
    "cypress:e2e": "npm run start & wait-on http://localhost:8080 && npm run test:e2e && npm run stop"
}

Please help to write npm script "stop" .请帮助编写 npm 脚本"stop"

Better solutions or approaches would be appreciated.更好的解决方案或方法将不胜感激。


Solutions tried:尝试的解决方案:

"stop": "kill -SIGINT %1"

I still have the process running :我仍然有进程在运行:

在此处输入图片说明

There are several ways to do this.有几种方法可以做到这一点。

Use pkill :使用pkill

pkill -SIGINT -f server.ts

This way, you do not need to know the PID of the process.这样,您就不需要知道进程的 PID。 However, this will send a signal to all processes that have "server.ts" in the command line.但是,这将向命令行中具有“server.ts”的所有进程发送信号。

Use a pidfile使用pid文件

In server.ts , write process.pid to a pidfile, for example server.pid .server.ts ,将process.pid写入 pidfile,例如server.pid Then use the pidfile to send a signal.然后使用pidfile发送信号。

pkill -SIGINT --pidfile server.pid

This can also be done from Node.js with process.kill() .这也可以从 Node.js 使用process.kill()

You should remove the pidfile when the server process exits.当服务器进程退出时,您应该删除 pidfile。

Use an endpoint使用端点

In server.ts add a route to shutdown the server.server.ts添加一个关闭服务器的路由。

app.post('/shutdown', (req, res) => {
  res.sendStatus(200);
  process.exit(0);
});

Then send a request to this endpoint at the end of the e2e tests or from the command line with curl .然后在 e2e 测试结束时或从命令行使用curl向此端点发送请求。

You should probably only enable this endpoint in development and not in production.您可能应该只在开发中而不是在生产中启用此端点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM