gpt4 book ai didi

node.js - 创建可停止的 Linux 服务

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:19:28 24 4
gpt4 key购买 nike

我正在尝试将 NodeJS 应用程序作为 Linux 服务运行。我在 /etc/init.d 文件夹下创建了一个服务文件,内容如下:

#!/bin/bash
# chkconfig: 2345 20 80
# description: Description comes here....

# Source function library.
. /etc/init.d/functions

start() {
# code to start app comes here
# example: daemon program_name &
/usr/bin/node /home/folder/nodeapp.js &
echo "Service started">&2
}

stop() {
# code to stop app comes here
# example: killproc program_name
killproc /usr/bin/node
echo "Service stopped">&2
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
status)
# code to check status of app comes here
# example: status program_name
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
esac

这是它运行的 JS 文件:

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("aa1");
}).listen(8081);

我可以启动该服务并且运行良好。问题是我不知道如何正确停止它。上面的停止函数实际上会杀死 Node 进程(node.exe),因此所有 Node 应用程序都会自动停止。我只需要停止我的 nodeapp.js。

所以我需要这样的东西:

stop() {
# code to stop app comes here
# example: killproc program_name
killproc /usr/bin/node /home/folder/nodeapp.js
echo "Service stopped">&2
}

当然,它不起作用。

顺便说一句,请不要推荐使用 systemctl 或类似的新东西。我知道这更容易,但我必须使用旧版本的 CentOS。

最佳答案

执行此操作的经典方法是在启动后直接将进程 ID 号写入文件 (echo $! >/var/run/myapp.pid)。要停止它,请读回文件并kill PID。

关于node.js - 创建可停止的 Linux 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45644774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com