调试NodeJS子进程的VSCode babel-node

时间:2019-02-06 23:09:59

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

我在babel-node中将runtimeExecutable用于launch.json,如this answer所示。这样做的原因是因为我正在使用ES6导入,并且由于转译和源映射,在VSCode中移动了断点。

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。当跳过传递新进程的行时,在控制台中出现此错误:

  

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

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

在“消息”事件的回调中,我在 one.js two.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 =开发$(npm bin)/ babel-node index.js

我得到输出:

enter image description here

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

但是,当尝试调试它时,我得到不同的结果,并且else条件下的断点从未与“我是新手!”一起出现。永远不会被记录。调试时的命令为:

  

babel节点--nolazy --inspect-brk = 33597 index.js

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

enter image description here

1 个答案:

答案 0 :(得分:0)

我最终使它开始工作,并且我怀疑是babel-node引起了该问题。我在自己的 launch.json 中将babel-node删除为runtimeExecutable,而是添加了@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"]
        }
    ]
}

即使这是问题所在,我仍然不确定为什么 这是问题所在。如果有人能够找到原因所在,那么我将很高兴地向您颁发赏金……否则,这将浪费您的时间:)