如何实现Deno脚本崩溃后自动重启?求对应Node实现的Deno等价代码
Deno脚本崩溃自动重启的等价实现
以下Node.js代码可实现脚本崩溃后自动重启:
import { spawn } from 'node:child_process'; process.on( 'uncaughtException', () => { process.once( 'exit', () => spawn( process.argv.shift(), process.argv, { cwd: process.cwd(), detached: true, stdio: 'inherit' } ) ); process.exit(); } );
对应的Deno等价代码需要覆盖同步未捕获异常和未处理的Promise拒绝两种场景——仅监听unhandledRejection无法处理同步代码抛出的异常,因此需要同时监听两个事件:
import { spawn } from "deno:child_process"; // 监听同步代码的未捕获异常 Deno.addListener("uncaughtException", restartProcess); // 监听未处理的Promise拒绝 Deno.addListener("unhandledRejection", restartProcess); function restartProcess() { // 绑定一次性退出事件,避免重复触发 Deno.addListener("exit", () => { spawn(Deno.execPath(), Deno.args, { cwd: Deno.cwd(), detached: true, stdio: "inherit", }); }, { once: true }); Deno.exit(); }
关键说明:
- 使用
Deno.execPath()获取当前Deno可执行文件路径,替代Node中的process.argv.shift() Deno.args直接获取脚本的命令行参数,对应Node的process.argv- 同时监听
uncaughtException和unhandledRejection,覆盖所有未捕获错误场景 - 通过
{ once: true }确保退出事件仅触发一次,避免重复启动进程
内容的提问来源于stack exchange,提问作者KaKi87
相关产品推荐
相关产品推荐

