代码调试

994 阅读2分钟

调试node.js源码

目的:调试node内置库:child_process.exec方法

需要调试的js文件:bin/process/index.js

const cp = require("child_process");
cp.exec("ls -al | grep node_modules", function (err, stdout, stdError) {
  console.log("exec", stdout.toString());
});

方法一:终端+chrome浏览器

不好用

  • 终端启动命令: node --inspect=9222 bin/process/index.js
  • chrome浏览器访问 chrome://inspect/#devices

iShot2021-12-02 11.20.07.png

点击inspect

iShot2021-12-02 11.21.10.png

调试进入node内置方法child_process.exec

iShot2021-12-02 11.21.10.png

方法二:.vscode/launch.json

不好用 虽然调试源码不好用, 但是调试package.json中scripts很实用。

ex: 调试命令npm run test ./util.test.js 该命令会调试Jest内容,相当于运行jest run test ./util.test.js

  1. 打上vscode断点
  2. 方法一、在vscode编辑页面点击F5,左侧栏有文字提示"To customize Run and Debug create a launch.json file.", 点击文字提示,选择Node.js,自动创建.vscode/launch.json文件,或者自己手动新建(F5的快捷键:vscode左Debugger栏,点击"Run and Debug", "start debugging")
    • 在左侧栏Debugger按钮的dropdown list里面选择要Debugger的命令,会自动运行Debugger命令,会跳出Terminal的运行台是JavaScript Debugger运行台
  3. 方法二、直接+ JavaScript DebuggerTerminal,手动运行npm run test
    • 在vscode左侧Debugger栏会看到No Configuration的Debugger按钮, 点击按钮选择Node.js,vscode会弹框提示
      • Variable ${file} can not be resolved. Please open an editor.
    • 点击open Launch,会自动新建.vscode/launch.json文件,需要手动配置configuration才能work(配置runtimeArgs)
    • 之后运行npm run test, 会Debugger到断点处 .vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
      {
        "type": "node",
        "request": "launch",
        "name": "Launch npm run test",
        "cwd": "${workspaceRoot}",
        "runtimeExecutable": "npm",
        "runtimeArgs": [
            "run-script", "test"
        ],
        "port": 5858
  
      },
      {
          "request": "attach"
      }
  ]
}

方法三:webstorm

好用

  • 在webstorm内部对node有很好的支持,可以直接进入node.js内部

进行设置

Preferences-搜索node-勾选Coding assistance for Node.js iShot2021-12-02 13.49.02.png

Preferences-Build, Execution, Deployment-Debugger-Stepping-不勾选Do not step into library scripts和Do not step into scripts iShot2021-12-02 13.55.39.png

Debug配置:

创建一个调试并配置它:Run-Edit Configurations-Add new Configurations

配置debug1.png

debug调试2.png

配置完成就可以,打断点并run debug,也可以进入node内置库,查看源码。

如果调试脚手架命令,则可以配置Node parameters: 入口文件 空格 命令参数。比如cli.js ls

  • 查看当前变量

iShot2021-12-02 14.39.08.png

  • debug进入内置库查看源码

iShot2021-12-02 14.18.42.png

lerna源码调试

  • 找到bin对应的入口文件
  • 在入口文件处打上断点
  • 编辑debug配置
    • 例如调试命令lerna ls iShot2021-12-06 14.23.04.png

iShot2021-12-06 14.24.49.png

iShot2021-12-06 14.21.43.png

lernals.png

  • 运行调试命令

iShot2021-12-06 14.37.03.png

调试网页代码

传送门