调试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
点击inspect
调试进入node内置方法child_process.exec
方法二:.vscode/launch.json
不好用 虽然调试源码不好用, 但是调试package.json中scripts很实用。
ex: 调试命令npm run test ./util.test.js 该命令会调试Jest内容,相当于运行jest run test ./util.test.js
- 打上vscode断点
- 方法一、在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运行台
- 在左侧栏Debugger按钮的dropdown list里面选择要Debugger的命令,会自动运行Debugger命令,会跳出
- 方法二、直接+
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
- 在vscode左侧Debugger栏会看到No Configuration的Debugger按钮, 点击按钮选择Node.js,vscode会弹框提示
{
"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
Preferences-Build, Execution, Deployment-Debugger-Stepping-不勾选Do not step into library scripts和Do not step into scripts
Debug配置:
创建一个调试并配置它:Run-Edit Configurations-Add new Configurations
配置完成就可以,打断点并run debug,也可以进入node内置库,查看源码。
如果调试脚手架命令,则可以配置Node parameters: 入口文件 空格 命令参数。比如cli.js ls
- 查看当前变量
- debug进入内置库查看源码
lerna源码调试
- 找到bin对应的入口文件
- 在入口文件处打上断点
- 编辑debug配置
- 例如调试命令
lerna ls
- 例如调试命令
- 运行调试命令