简体   繁体   English

如何在 VSCode 中调试 nodemon 项目

[英]How to debug a nodemon project in VSCode

I have a NodeJs project and I run it using nodemon,我有一个 NodeJs 项目,我使用 nodemon 运行它,
I wish to run it in debug mode for development tasks, but I am unable to do so.我希望在调试模式下运行它以执行开发任务,但我无法这样做。

I found that I'll need to add the right configuration to the launch.json file under.vscode folder,我发现我需要在.vscode文件夹下的launch.json文件中添加正确的配置,
I have a app.js file which is the main app file.我有一个app.js文件,它是主应用程序文件。
And the application runs on node version 4.6.2 and on Port 8080 .该应用程序在node version 4.6.2Port 8080上运行。
In usual case I run the App using npm run dev command.通常情况下,我使用npm run dev命令运行应用程序。

Following is my launch.json file -以下是我的 launch.json 文件 -

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "MyApp",
            "program": "${workspaceFolder}/app.js",
            "runtimeVersion": "4.6.2",
            "protocol": "legacy",
            "port": 8080
            //"runtimeExecutable": "/home/user/.nvm/versions/node/v4.6.2/bin/node"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "nodemon",
            "runtimeExecutable": "nodemon",
            "program": "${workspaceRoot}/app.js",
            "restart": true,
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen",
            "runtimeVersion": "4.6.2",
            "protocol": "legacy",
            "port": 8080
        },
        {
            "type": "node",
            "request": "launch",
            "name": "DEBUG",
            "runtimeExecutable": "nodemon",
            "program": "${workspaceFolder}/app.js",
            "restart": true,
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen",
            "runtimeVersion": "4.6.2",
            "protocol": "legacy",
            "port": 8080
        }
    ]
}

The package.json is as follows - package.json如下——

{
  "name": "myapp",
  "description": "myapp",
  "version": "1.35.0",
  "private": true,
  "scripts": {
    "dev": "nodemon app.js",
    "debug": "nodemon app.js"
  },
  "dependencies": {
    "async": "1.3.0",
    "aws-sdk": "2.7.20",
    "aws-xray-sdk": "^2.1.0",
    "aws-xray-sdk-restify": "^1.3.0-beta",
    "bcrypt": "0.8.5",
    "body-parser": "1.12.3",
    "compression": "^1.7.0",
    "connect-flash": "0.1.1",
    "cookie-parser": "1.3.4",
    "cron": "1.0.9",
    "csurf": "^1.9.0",
    "csvtojson": "^1.1.2",
    "date-utils": "1.2.16",
    "dotenv": "4.0.0",
    "email-templates": "1.2.1",
    "express": "4.12.3",
    "express-handlebars": "2.0.0",
    "express-jwt": "^5.1.0",
    "express-mailer": "0.2.4",
    "express-session": "1.11.1",
    "express-validator": "3.1.3",
    "handlebars": "^3.0.3",
    "helmet": "^3.5.0",
    "html-pdf": "1.4.0",
    "json-2-csv": "2.0.12",
    "jsonwebtoken": "^7.3.0",
    "multer": "^0.1.8",
    "mysql": "2.6.2",
    "newrelic": "1.25.0",
    "node-schedule": "^1.3.0",
    "nodemailer": "^1.3.4",
    "nodemailer-ses-transport": "1.2.0",
    "passport": "0.2.1",
    "passport-local": "1.0.0",
    "path": "0.11.14",
    "promise": "7.0.0",
    "qs": "^2.4.1",
    "replaceall": "0.1.6",
    "request": "2.55.0",
    "run-parallel": "1.1.0",
    "validator": "^7.0.0",
    "winston": "^2.3.1",
    "winston-daily-rotate-file": "^1.7.0",
    "xlsx": "0.8.8"
  },
  "devDependencies": {
    "nodemon": "^1.17.3"
  }
}

The App gets launched when I run the DEBUG and nodemon configurations,当我运行 DEBUG 和 nodemon 配置时,应用程序启动,
But the code is not getting paused on the breakpoints I put on the app.js file.但是代码并没有在我放在 app.js 文件上的断点处暂停。

Reference links -参考链接——
1.https://github.com/Microsoft/vscode-recipes/tree/master/nodemon 1.https://github.com/Microsoft/vscode-recipes/tree/master/nodemon
2. https://github.com/bdspen/nodemon_vscode 2. https://github.com/bdspen/nodemon_vscode
3. Can Visual Studio Code be configured to launch with nodemon 3. Visual Studio Code 是否可以配置为使用 nodemon 启动
4. Cannot debug in VSCode by attaching to Chrome 4. VSCode 无法通过附加到 Chrome 进行调试
5. https://code.visualstudio.com/docs/editor/debugging 5. https://code.visualstudio.com/docs/editor/debugging

What changes are required in package.json, or any corrections in Launch configuration - launch.json, that would help me to debug the application in VSCode for my usecase? package.json 中需要进行哪些更改,或者启动配置中的任何更正 - launch.json,这将有助于我在 VSCode 中为我的用例调试应用程序?

Change package.json to将 package.json 更改为

"scripts": {
    "dev": "node app.js",
    "debug": "nodemon --inspect app.js"
}

--inspect is for versions >= 6.3. --inspect 适用于 >= 6.3 的版本。 --legacy or --auto for older versions --legacy 或 --auto 用于旧版本

And launch.json to:并发射.json 到:

"version": "0.2.0",
"configurations": [
    {
        "type": "node",
        "request": "attach",
        "name": "Node: Nodemon",
        "processId": "${command:PickProcess}",
        "restart": true,
        "protocol": "inspector"
    }
]

the restart flag is the key here.重启标志是这里的关键。

Start app via new debug script通过新的调试脚本启动应用程序

npm run debug npm 运行调试

  • In Debug view, select the Node: Nodemon configuration and press play or F5在 Debug 视图中,select Node: Nodemon配置并按播放或 F5
  • Choose the process started above选择上面启动的进程

See more:vscode nodemon recipe查看更多:vscode nodemon 配方

In vscode config, you can set the runtimeExecutable which will run the program you give.在 vscode 配置中,您可以设置运行您提供的程序的runtimeExecutable set restart:true so vs code debugger can restart the process.设置restart:true以便 vs 代码调试器可以重新启动进程。

This is an example config:这是一个示例配置:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node", 
            "request": "launch",
            "name": "nodemon",
            "runtimeExecutable": "nodemon",
            "program": "${workspaceFolder}/bin/www",
            "restart": true,
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen",
            "env": {
                "debug": "app:*",
            }
        }
    ]
}

Update program to the node file you want to debug.program更新到要调试的节点文件。

It's easy than attaching a debugger to the running node process.这比将调试器附加到正在运行的节点进程要容易。

I ran into a similar issue attaching to a Dockerized nodemon process.我遇到了附加到 Dockerized nodemon 进程的类似问题。 I found the solution in this article .我在这篇文章中找到了解决方案。 I was able to get it working by changing three things:我能够通过改变三件事让它工作:

  1. Added --inspect=0.0.0.0 to the npm script that launched the service (named debug in my case):在启动服务的 npm 脚本中添加--inspect=0.0.0.0 (在我的例子中名为debug ):
  "scripts": {
    "debug": "nodemon -w lib -w server.js --inspect=0.0.0.0 server.js"
  }
  1. Making sure port 9229 (or whatever debug port you wish to use) is open in the Docker container.确保在 Docker 容器中打开端口 9229(或您希望使用的任何调试端口)。 I'm using docker-compose , so it's defined in the associated yaml:我正在使用docker-compose ,所以它在相关的 yaml 中定义:
ports:
  - "8080:8080"
  - "9229:9229"
  1. Adding the following configuration to launch.json in VS Code:将以下配置添加到 VS Code 中的launch.json中:
    "configurations": [
        {
            "name": "Attach to Node in Docker",
            "type": "node",
            "address": "localhost",
            "port": 9229,
            "request": "attach",
            "restart": true
        }
    ]

The "restart": true option allows the debugger to automatically reattach when nodemon recompiles things after a watched file changes. "restart": true选项允许调试器在 nodemon 在监视文件更改后重新编译时自动重新附加。

You can launch and attach nodemon with F5, however it will require a little more setup.您可以使用 F5 启动和附加 nodemon,但它需要更多设置。

We will have to first pre-launch nodemon via VS Code task and then attach.我们必须首先通过 VS Code 任务预启动 nodemon,然后附加。

I'm using remote debugger to attach since it does not require additional clicks to select the process to attach, and VS Code process picker is currently broken in WSL2 , which is my main development environment.我正在使用远程调试器进行附加,因为它不需要额外点击 select 附加过程,并且 VS Code 进程选择器目前在 WSL2 中损坏,这是我的主要开发环境。

tasks.json (from this answer ): tasks.json(来自这个答案):

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "npm dev",
      "type": "npm",
      "script": "dev",
      "isBackground": true,

      // This task is run before some debug tasks.
      // Problem is, it's a watch script, and since it never exits, VSCode
      // complains. All this is needed so VSCode just lets it run.
      "problemMatcher": [
        {
          "pattern": [
            {
              "regexp": ".",
              "file": 1,
              "location": 2,
              "message": 3
            }
          ],
          "background": {
            "activeOnStart": true,
            "beginsPattern": ".",
            "endsPattern": "."
          }
        }
      ]
    }
  ]
}

launch.json:发射.json:

{
  "type": "node",
  "request": "attach",
  "name": "Launch & Attach",
  "restart": true,
  "localRoot": "${workspaceRoot}",
  "remoteRoot": "${workspaceRoot}",
  "preLaunchTask": "npm dev"
}

And in npm dev script (for node >= 6.9):在 npm 开发脚本中(对于节点 >= 6.9):

nodemon --watch src -e js --exec node --inspect .

Note - this approach won't work if your process takes more than 10 seconds to start.注意 - 如果您的流程启动时间超过 10 秒,此方法将不起作用。 In that case you will have to figure out how to signal VS Code when the pre-launch task has finished.在这种情况下,您必须弄清楚如何在预启动任务完成时向 VS Code 发出信号。 This probably can be achieved by playing with beginsPattern / endPattern regex, though I haven't tried it.这可能可以通过使用 beginPattern / endPattern 正则表达式来实现,尽管我没有尝试过。

nodemon listens to files changes and re-start the app on another process nodemon 侦听文件更改并在另一个进程上重新启动应用程序

So your configuration is correct but the debugger never "sees" the breakpoints.所以你的配置是正确的,但调试器永远不会“看到”断点。

There is no point of running debug mode with nodemon.使用 nodemon 运行调试模式毫无意义。

That's is a feature you may want to request on VScode(Auto-Restart on code change)这是您可能希望在 VScode 上请求的功能(代码更改时自动重启)

As @the Geek proposes,正如@the Geek 建议的那样,

  1. You should modify launch.json as follows:您应该修改 launch.json 如下:

     { "version": "0.2.0", "configurations": [ { "type": "node", "request": "attach", "name": "Attach by Process ID", "processId": "${command:PickProcess}" } ] }
  2. Start server "npm run dev" (as you can see, in "request" property, we set to attach. So we have to run the server firstly and then attach the debugger).启动服务器“npm run dev”(如您所见,在“请求”属性中,我们设置为附加。所以我们必须先运行服务器,然后附加调试器)。

  3. Click on the left side of vscode in the bug-like icon.在类似 bug 的图标中点击 vscode 的左侧。 On top you will see the small green play icon.在顶部,您会看到绿色的小播放图标。 Click on the dropdown arrow right of it and select "Attach by process ID".单击它右侧的下拉箭头和 select “按进程 ID 附加”。

  4. Click on the play icon and then a bar on the bottom of vscode should turn dark orange.单击播放图标,然后 vscode 底部的条应变为深橙色。 Now try making a request.现在尝试提出请求。 Breakpoints will be hit correctly断点将被正确命中

In 2022 i use this:在 2022 年,我使用这个:

// launch.json
"configurations": [
        {
            "name": "Launch via NPM",
            "request": "launch",
            "runtimeArgs": ["run", "debug"],
            "runtimeExecutable": "npm",
            "skipFiles": ["<node_internals>/**"],
            "type": "node"
        }
    ]
// package.json
"scripts": {
        "debug": "nodemon dist/app"
    }

After this I click Run and Debug: Launch via NPM in vscode.在此之后,我单击Run and Debug: Launch via NPM And the debugger starts with nodemon and the breakpoints working when code changes.调试器从 nodemon 开始,代码更改时断点工作。

I was searching for the same problem and encountered this question, as now in 1. July 2022, this seems to be the best way.我正在寻找同样的问题并遇到了这个问题,就像现在在 2022 年 7 月 1 日一样,这似乎是最好的方法。 Using the Auto-Attach feature in VSCode.使用 VSCode 中的自动附加功能。

I followed the article here , restarted the IDE, set a breakpoint, and ran my code with:我按照这里的文章,重新启动 IDE,设置断点,然后运行我的代码:

nodemon app.js

everything worked correctly as expected.一切都按预期正常工作。

so Proccess:所以过程:

  Activating Auto Attach -> Restarting IDE -> Setting Break Points-> Running with Nodemon

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM