Node 程序远程调试

1,252 阅读1分钟

Node 程序远程调试

一、远程服务器 Node 操作

1、远程服务器 Node Js 代码

// index.js
function doit () {
    console.log('start-->');
    debugger;
    console.log('end');
    for(let i = 0; i < 5; i++) {
        console.log(i);
    }
};
doit();

2、通过 --inspect-brk=[host:port] 运行 Node Js 程序

1. 在远程服务器运行当前 Node 程序
node --inspect-brk=0.0.0.0:9229 index.js
2. ifconfig 查找远程服务器 IP 地址

二、在当前服务器中的 Chrome 浏览器中调试

1. 打开 Chrome 浏览器,输入 chrome://inspect 并打开
2. 点击 Configure... 按钮

image.png

3. 配置 Configure 远程服务器 IP: Port,并保存

image.png

4. 可以看到在 Remote Target 中展示远程服务器的信息

remote target

5. 点击 inspect 按钮,就可以开始调试了

image.png

三、在当前服务器中的 VScode 中进行调试

1. 使用 VScode 打开一个文件夹

2. 在当前文件夹的 .vscode 文件夹中 launch.json 文件中新建配置

如果没有此文件夹和文件,请新建 vscode

launch.json 初始配置

{
    // 使用 IntelliSense 了解相关属性。 
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        
    ]
}

3. 点击添加配置按钮

image.png

4. 选择 Attach to Remote Program

image.png

选完之后的 json 配置

{
    // 使用 IntelliSense 了解相关属性。 
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "address": "TCP/IP address of process to be debugged",
            "localRoot": "${workspaceFolder}",
            "name": "Attach to Remote",
            "port": 9229,
            "remoteRoot": "Absolute path to the remote directory containing the program",
            "request": "attach",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "type": "pwa-node"
        }
    ]
}

5. 把当前 address 改为远程服务器的 IP 即可,然后点击图中 1,再点图中 2

image.png

6. 远程服务器的 Node 代码就运行在当前 Vscode 中了

image.png

参考