You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 08:45:07