您的位置:首页 > Web前端 > Node.js

vscode中调试node.js项目

2018-02-20 21:32 519 查看
vscode调试node.js项目一般有三种情况:

1.vscode启动调试服务端,直接运行要调试的入口文件,开发时比较适合,目前好像只能运行js文件,ts文件可能有点难度

2.远程调试,需要远程服务端以调试模式先运行起来,然后本地根据host、post连接远程调试服务器

3.本地根据进程调试,需要本地服务端先运行起来,然后本地根据进程id附加到指定进行调试,不需要服务端以调试模式运行

vscode中内置了这几种方式的配置:

1.直接本地以调试模式运行服务端,同时运行调试客户端连接

直接以node命令运行:

调试运行框->添加配置->Node.js:启动程序,生成配置如下:

{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}\\index.js"
}其中选项:
type:代表调试环境,node、python、c++等

request:代表行为,launch为直接运行入口文件,attach为附加到远程调试客户端,或者附加到本地进程

runtimeExecutable:运行时,即运行的命令,node、nodemon等,type为node时默认为node可以省略

runtimeArgs:运行参数,传递给运行时

program:代表运行的脚本

运行调试的输出:

node --inspect-brk=41886 index.js
Debugger listening on ws://127.0.0.1:41886/44ec2627-9ddf-44a8-8eb5-19389d2b57d5
说明程序以调试模式启动,且随机指定了调试端口,而且调试信息以websocket协议传输,vscode的调试客户端就是连接到这个调试端口的

直接以nodemon命令运行:

调试运行框->添加配置->Node.js:Nodemon安装程序,生成配置如下:

{
"type": "node",
"request": "launch",
"name": "nodemon",
"runtimeExecutable": "nodemon",
"program": "${workspaceFolder}/index.js",
"restart": true,
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}看到运行时为nodemon,restart为true,应该为nodemon专属参数
运行调试的输出:

[nodemon] starting `node --inspect=48487 --debug-brk index.js`
Debugger listening on ws://127.0.0.1:48487/60beffd8-d508-4fd4-97e2-1126ce113733
For help see https://nodejs.org/en/docs/inspector Debugger attached.nodemon内部执行了相同的node命令

2.附加到远程服务端调试

调试运行框->添加配置->Node.js:附加到远程计划,生成配置如下:

{
"type": "node",
"request": "attach",
"name": "Attach to Remote",
"address": "localhost",
"port": 27965,
"localRoot": "${workspaceFolder}",
"remoteRoot": "Absolute path to the remote directory containing the program"
}最后两个选项暂时不管,没用到,主要:
address:远程调试服务端域名

port:远程调试端口

启动调试服务端:

node --inspect-brk=27965 index.js
Debugger listening on ws://127.0.0.1:27965/be5ec018-fa58-4948-9f8d-c648c8f2dc83
For help see https://nodejs.org/en/docs/inspector启动调试: Debugger attached.说明调试器附加上了
这里还有一些说明:

nodemon启动调试:
nodemon --inspect-brk=27965输出:
[nodemon] starting `node --inspect-brk=27965 index.js`
Debugger listening on ws://127.0.0.1:27965/14488469-286f-411e-a73a-d49ea5d8effa
For help see https://nodejs.org/en/docs/inspector说明nodemon命令的调试选项会传递给node命令,而默认参数为index.js
3.附加到指定进程调试

调试运行框->添加配置->Node.js:附加到进程,生成配置如下:
{
"type": "node",
"request": "attach",
"name": "Attach by Process ID",
"processId": "21920"
}只有一个进程id需要稍微理解一下
启动项目:

node index.js运行调试:
Debugger listening on ws://127.0.0.1:9229/6cf17f3e-8844-43eb-b3c4-aab3dd59af8a
For help see https://nodejs.org/en/docs/inspector Debugger attached.

这里还有最后一个问题:ts项目目前好像不能直接使用ts-node运行进行调试,必须经过index.js
require('ts-node/register');
require('./src/main');即入口文件只能是js,或者说我还不会直接在调试时运行ts
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: