【问题标题】:Debugging NodeJS child process' VSCode babel-node调试 NodeJS 子进程的 VSCode babel-node
【发布时间】:2019-07-01 00:23:49
【问题描述】:

我在launch.json 中使用babel-node 作为我的runtimeExecutable,如this answer 所示。这样做的原因是因为我在 VSCode 中使用 ES6 导入和断点,因为转译和源映射会四处移动。

launch.json

{
    "version": "0.2.0",
    "configurations": [{
        "type": "node",
        "request": "launch",
        "name": "Debug",
        "autoAttachChildProcesses": true,
        "program": "${workspaceFolder}/index.js",
        "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/babel-node",
        "runtimeArgs": [
            "--nolazy"
        ],
        "env": {
            "BABEL_ENV": "debug"
        }
    }]
}

app.js (我在其中派生子进程)

(async () => {
    const process1 = fork(path.join(__dirname, "children", "process", "one.js"));
    const process2 = fork(path.join(__dirname, "children", "process", "two.js"));

    process1.send("start");
    process2.send("start");
})();

one.js/two.js

process.on("message", async (message) => {
    console.log("message - " + message);
    await init();
});

文件的内容不太重要,但我想我还是会把它们放在那里。我可以完美地调试app.js 的IIFE。当跳过通过我 fork 新进程的行时,我在控制台中收到此错误:

错误:未知选项 `--inspect-brk'

我从this answer 中获取了autoAttachChildProcesses 规则,但我假设babel-node 有复杂的事情。

我在 "message" 事件的回调中的 one.jstwo.js 都有断点,但它们变成了未验证的断点当我初始化调试时。

编辑

我现在已经改为使用 NodeJS cluster 模块而不是 child_process 纯粹是因为我发现的所有示例都使用 cluster 代替。

我现在的 launch.json 配置:

{
    "type": "node",
    "request": "launch",
    "name": "Debug 2",
    "autoAttachChildProcesses": true,
    "stopOnEntry": false,
    "program": "${workspaceFolder}/index.js",
    "runtimeExecutable": "${workspaceFolder}/node_modules/.bin/babel-node",
    "console": "internalConsole",
    "runtimeArgs": [
        "--nolazy"
    ],
    "env": {
        "BABEL_ENV": "debug"
    },
    "skipFiles": [
        "node_modules/**/*.js",
        "<node_internals>/**/*.js"
    ]
}

项目初始化index.js:

require("dotenv").config();
console.log("::: index.js :::");

require("./src/app.js")

src/app.js

import express from "express";
import session from "express-session";
import bodyParser from "body-parser";
import morgan from "morgan";
import cors from "cors";
import chalk from "chalk";
import cluster from "cluster";

const app = express();
const log = console.log;
const numCpus = 4;
console.log("::: app.js :::");

console.log(`::: Master or Worker?: ${(cluster.isMaster) ? "Master" : "Worker"}`);
if (cluster.isMaster) {
    app.use(bodyParser.json());
    app.use(morgan("combined"));
    app.use(cors());
    app.use(session({
        secret: "test",
        resave: false,
        saveUninitialized: true,
    }));

    app.listen(process.env.PORT || 3000, () => {
        log(chalk.green("--------------------"));
        log(chalk.green(`Host:\t${process.env.HOST || "localhost"}`));
        log(chalk.green(`Port:\t${process.env.PORT || 3000}`))
        log(chalk.green("--------------------"));
    });

    for (let i = 0; i < numCpus; i++) {
        console.log("::: forking :::");
        cluster.fork();
    }

    cluster.on("online", (worker) => {
        console.log(`Worker ${worker.id} is now online after it has been forked`);
    });
    cluster.on("listening", (worker, address) => {
        console.log(`A worker is now connected to ${address.address}:${address.port}`);
    });
    cluster.on("fork", (worker) => {
        console.log(`New worker being forked: ${worker.id}`)
    });
    cluster.on("exit", (worker, code, signal) => {
        console.log(`Worker ${worker.id} died ${signal || code}`);
    });
    cluster.on("death", (worker) => {
        console.log(`Worker ${worker.id} died`)
    });
} else {
    require("./worker.js")
}

export default app;

src/worker.js

console.log("I'M A NEW WORKER!")

如果我从终端运行npm run start:dev,它会运行:

NODE_ENV=development $(npm bin)/babel-node index.js

我得到了输出:

这对我来说似乎是正确的,所以集群的设置似乎是正确的。

然而,当尝试调试它时,我得到了不同的结果,并且else 条件中的断点永远不会与“我是新员工!”一起被击中。从不记录。调试时的命令是:

babel-node --nolazy --inspect-brk=33597 index.js

我在 src/app.jsindex.js 周围放置了断点。最初,一切似乎都还好,但在 for 循环完成并且两个 cluster.fork()s 都已运行之后,发生了一件奇怪的事情。调试返回并点击 parent 进程的 index.js。在此之前,子进程存在于调用堆栈中,但仅存在一定时间(但没有控制台日志显示它们已退出)。在此之后,调试器说它仍在运行,但没有遇到断点。 src/worker.js 中的断点未验证。结果,我在控制台看到的所有日志都是:

【问题讨论】:

    标签: javascript node.js visual-studio-code child-process


    【解决方案1】:

    我最终让它工作了,我怀疑是babel-node 导致了这个问题。我从 launch.json 中的 runtimeExecutable 中删除了 babel-node,而是添加了 @babel/register 作为编译的命令行参数。我的最终 launch.json 如下所示:

    {
        "version": "0.2.0",
        "configurations": [
            {
                "type": "node",
                "request": "launch",
                "name": "Debug",
                "autoAttachChildProcesses": true,
                "program": "${workspaceFolder}/index.js",
                "console": "internalConsole",
                "runtimeArgs": ["--nolazy", "--require", "@babel/register"],
                "env": {
                    "BABEL_ENV": "debug",
                    "NODE_ENV": "debug"
                },
                "skipFiles": ["node_modules/**/*.js", "<node_internals>/**/*.js"]
            }
        ]
    }
    

    即使这是问题所在,我仍然不确定为什么这是问题所在。如果有人能够找到问题的原因,那么我会很高兴地奖励你赏金......否则它会浪费掉:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-21
      • 2020-10-24
      • 2018-01-10
      • 2017-06-17
      • 1970-01-01
      • 2019-04-01
      • 2016-11-28
      • 2021-05-11
      相关资源
      最近更新 更多