如何在Visual Studio代码中调试子Node.JS进程?

时间:2015-09-16 18:16:00

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

如何在VS Code中调试子Node.JS进程?
以下是我正在尝试调试的代码示例:

var spawn = require('child_process').spawn;
var scriptPath = './child-script.js';
var runner_ = spawn('node', [scriptPath]);

5 个答案:

答案 0 :(得分:17)

在启动配置中,如下所示添加"autoAttachChildProcesses": true

{
  "type": "node",
  "request": "launch",
  "name": "Launch Program",
  "autoAttachChildProcesses": true,
  "program": "${workspaceFolder}/index.js"
}

答案 1 :(得分:3)

您可以轻松地向launch.json添加新的启动配置,允许您使用特定端口附加到正在运行的节点实例:

{
        "name": "Attach to Node",
        "type": "node",
        "address": "localhost",
        "port": 5870,
}

请确保使用 - debug - debug-brk 参数派生/生成节点进程。

答案 2 :(得分:3)

在您的配置中进行以下更改, autoAttachChildProcess:true enter image description here

答案 3 :(得分:2)

寻找这个npm模块child-process-debug

我在vscode中创建了2个单独的启动配置:

一个用于主进程,另一个用于子进程

   {
        "name": "Attach",
        "type": "node",
        "request": "attach",
        "port": 5858,
        "address": "localhost",
        "restart": false,
        "sourceMaps": false,
        "outFiles": [],
        "localRoot": "${workspaceRoot}",
        "remoteRoot": null
    },
    {
        "name": "Attach child",
        "type": "node",
        "request": "attach",
        "port": 5859,
        "address": "localhost",
        "restart": false,
        "sourceMaps": false,
        "outFiles": [],
        "localRoot": "${workspaceRoot}",
        "remoteRoot": null
    }

工作流程如下:

  1. 使用--debug命令行开关启动主节点进程 $ node --debug master.js
  2. 使用master.js通过调试面板
  3. 附加到Attach节点进程
  4. child.js流程
  5. 中放置断点
  6. 快速与main进程分离并使用child附加到Attach child进程
  7. 为了进行调试,您可以使用setTimeout

    延迟在进程之间发送消息
    // master.js
    var child = child_process.fork(__dirname + './child.js')
    setTimeout(function() {
        child.send('...')
    }, 5000)
    

答案 4 :(得分:0)

只需将其添加到调试器配置文件中

{
  "type": "node",
  "request": "attach",
  "name": "Attach by Process ID",
  "processId": "${command:PickProcess}",
}

要将调试器附加到进程ID。运行此配置时,将提示进程列表,您可以在其中选择要附加调试器的进程。