我有一个node.js
脚本在控制台中可以正常运行并退出,但是如果我不在pm2
中调用process.exit()
它就无法退出。PM2配置如下:
{
name: "worker",
script: "./worker.js",
restart_delay: 60000,
out_file: "/tmp/worker.log",
error_file: "/tmp/worker_err.log"
},
我安装了why-is-node-running
来查看进程在预期退出后10秒钟仍在运行的原因,输出结果如下:
There are 9 handle(s) keeping the process running
# TLSWRAP
node:internal/async_hooks:200
# TLSWRAP
node:internal/async_hooks:200
# ZLIB
node:internal/async_hooks:200
/Users/r/code/app/node_modules/decompress-response/index.js:43 - const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();
file:///Users/r/code/app/node_modules/got/dist/source/core/index.js:586
file:///Users/r/code/app/node_modules/got/dist/source/core/index.js:768
file:///Users/r/code/app/node_modules/got/dist/source/core/index.js:786
# TLSWRAP
node:internal/async_hooks:200
# ZLIB
node:internal/async_hooks:200
/Users/r/code/app/node_modules/decompress-response/index.js:43 - const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();
file:///Users/r/code/app/node_modules/got/dist/source/core/index.js:586
file:///Users/r/code/app/node_modules/got/dist/source/core/index.js:768
file:///Users/r/code/app/node_modules/got/dist/source/core/index.js:786
# TLSWRAP
node:internal/async_hooks:200
# ZLIB
node:internal/async_hooks:200
/Users/r/code/app/node_modules/decompress-response/index.js:43 - const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();
file:///Users/r/code/app/node_modules/got/dist/source/core/index.js:586
file:///Users/r/code/app/node_modules/got/dist/source/core/index.js:768
file:///Users/r/code/app/node_modules/got/dist/source/core/index.js:786
# TLSWRAP
node:internal/async_hooks:200
# Timeout
node:internal/async_hooks:200
node:internal/async_hooks:468
node:internal/timers:162
node:internal/timers:196
file:///Users/r/code/app/worker.js:65
node:internal/process/task_queues:94
为什么Node没有退出?我该如何进一步调试?
PS:抱歉粘贴的内容较大。
更新
我已经成功地将其缩小到了一个有趣的2行代码:
import got from "got";
await got.post('https://anty-api.com/browser_profiles', {form: {a: 123}}).json();
以上代码在控制台运行时按预期抛出异常,但在由
pm2
调用时会一直运行。
更新2:
即使是空的应用程序文件也会重现这个问题。
got
模块。但我们没有实际的代码来看看出了什么问题。你能将其缩减到几行以重现问题并发布一些代码吗? - Wyckgot
将其作为异常抛出。您滑稽小巧的复制品没有处理此异常。pm2可以区分崩溃(由于未处理的异常)和干净的退出。那可能是怎么回事?比较:got.post('https://anty-api.com/browser_profiles', {form: {a: 123}}).json().catch(console.error);
(或在可等待的方法中使用try/catch)。 - Wyckapplication.exit()
时会观察到重启的原因。)如果这个问题在空的app.js中也出现了,那么你应该修改你的问题。 - Wyck