如何在VSCode中调试nodemon项目

51

我有一个NodeJs项目并使用nodemon运行它,
我希望以调试模式运行进行开发任务,但是我无法这样做。

我发现我需要在.vscode文件夹下的launch.json文件中添加正确的配置,
我有一个名为app.js的主应用程序文件。
应用程序在node版本4.6.2上运行,并在端口8080上运行。
通常情况下,我使用npm run dev命令运行应用程序。

以下是我的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
        }
    ]
}
{"name": "example", "version": "1.0.0", "description": "Example package.json", "main": "index.js", "scripts": {"test": "echo \"Error: no test specified\" && exit 1"}, "author": "Your Name", "license": "ISC"}
{
  "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"
  }
}

当我运行DEBUG和nodemon配置时,应用程序会启动,但代码没有在我放置在app.js文件上的断点处暂停。

参考链接 -
1. https://github.com/Microsoft/vscode-recipes/tree/master/nodemon
2. https://github.com/bdspen/nodemon_vscode
3. Can Visual Studio Code be configured to launch with nodemon
4. Cannot debug in VSCode by attaching to Chrome
5. https://code.visualstudio.com/docs/editor/debugging

针对我的使用情况,在package.json中需要进行哪些更改或在Launch配置 - launch.json中需要进行哪些更正,以帮助我在VSCode中调试应用程序?

10个回答

69

修改 package.json 为

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

--inspect适用于版本>=6.3。--legacy或--auto适用于旧版本,详见

并且需要使用launch.json来:

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

这里关键是重启标志。

通过新的调试脚本启动应用程序

npm run debug

  • 在调试视图中,选择Node: Nodemon配置,并按播放或F5键
  • 选择上面启动的进程

了解更多:vscode nodemon recipe


1
"--inspect 适用于版本 >= 6.3。--legacy 或 --auto 适用于旧版本" 是指当前版本为 v15 的 node - Timo
2
注意:你应该选择的进程不是nodemon,而是运行应用程序的node进程。 - Marc

23
在 vscode 的配置中,你可以设置 runtimeExecutable 来运行你提供的程序。设置 restart:true 以便 vs code 调试器可以重新启动进程。
以下是一个示例配置:
{
    "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:*",
            }
        }
    ]
}

program更新为要调试的节点文件。

这比连接到运行中的节点进程更容易。


5
我知道我们不应该只为了说“谢谢”而写评论,但是非常感谢你。在尝试很多不同的launch.json文件都没有成功之前,我不知道有多少个。不过,在我的情况下,我不得不将"${workspaceFolder}/bin/www"改为"${workspaceFolder}/server" - Sebastián Vansteenkiste
1
我了解到,当我像你的示例一样使用“launch”时,我需要与我的调试HTML文件相关的“program”键(但是你的“program”是指一个文件夹,而不是一个文件)。如果我像GeeK的另一个示例中使用“attach”,我需要“processId”并且选择我想要调试的进程(我之前用nodemon启动它)。 - Timo

13

我遇到了一个类似的问题,无法连接到一个运行在Docker容器中的nodemon进程。我在这篇文章中找到了解决方案。通过以下三个步骤,我成功地解决了这个问题:

  1. --inspect=0.0.0.0添加到启动该服务(在我的情况下是debug)的npm脚本中:
  "scripts": {
    "debug": "nodemon -w lib -w server.js --inspect=0.0.0.0 server.js"
  }
  1. 确保Docker容器中的端口9229(或您希望使用的任何调试端口)已打开。我正在使用docker-compose,因此在相关的yaml中定义了它:
ports:
  - "8080:8080"
  - "9229:9229"
  1. 将以下配置添加到VS Code中的launch.json文件中:
    "configurations": [
        {
            "name": "Attach to Node in Docker",
            "type": "node",
            "address": "localhost",
            "port": 9229,
            "request": "attach",
            "restart": true
        }
    ]
"restart": true选项允许调试器在nodemon重新编译更改后重新附加。

8

在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"
    }

然后我在 vscode 中点击 Run and Debug: Launch via NPM,调试器会使用 nodemon 启动,并在代码改变时断点正常工作。


你的 package.json 文件中是否有 nodemon:{} 的配置? - Alexey Nikonov

6

2022年到了。

在我编辑runtimeExecutable的值为以下内容之前,没有任何解决方案适用于我:

"runtimeExecutable": "${workspaceFolder}/node_modules/nodemon/bin/nodemon.js",

这将产生:

{
  "name": "debug nodemon",
  "type": "node",
  "request": "launch",
  "runtimeExecutable": "${workspaceFolder}/node_modules/nodemon/bin/nodemon.js",
  "program": "${workspaceFolder}/app.js",
  "restart": true,
  "console": "integratedTerminal",
  "internalConsoleOptions": "neverOpen"
},

3

您可以使用 F5 启动并附加 nodemon,但这需要进行一些额外的设置。

我们需要通过 VS Code 任务首先预启动 nodemon,然后再进行附加。

我使用远程调试器进行附加,因为它不需要额外的点击来选择要附加的进程,而且 VS Code 进程选择器目前在我的主要开发环境 WSL2 中存在问题(参见此问题)。

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:

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

在npm dev脚本中(适用于Node版本>=6.9):
nodemon --watch src -e js --exec node --inspect .

注意-如果您的过程启动需要超过10秒钟,那么这种方法将不起作用。 在这种情况下,您将不得不找出如何在预启动任务完成时向VS Code发出信号。尽管我没有尝试过,但可能可以通过对beginsPattern / endPattern正则表达式进行调整来实现这一点。

2
如@the Geek所提出的,
  1. You should modify launch.json as follows:

    {
        "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).

  3. Click on the left side of vscode in the bug-like icon. On top you will see the small green play icon. Click on the dropdown arrow right of it and select "Attach by process ID".

  4. Click on the play icon and then a bar on the bottom of vscode should turn dark orange. Now try making a request. Breakpoints will be hit correctly!


1

nodemon监听文件更改并在另一个进程上重新启动应用程序。

因此,您的配置是正确的,但调试器从未“看到”断点。

使用nodemon运行调试模式没有意义。

这是您可能希望在VScode上请求的功能(代码更改时自动重启)。


那么,我需要做哪些更改才能以调试模式运行它?在 package.json 或 launch.json 中是否有任何更改可以帮助我进行调试? - Ani
更改 launch.json 文件。使用 node 作为可执行文件,调试器将在断点处启动和停止。(就像 launch.json 中的第一个成员一样) - Mazki516
使用"runtimeExecutable": "node",而不是"runtimeExecutable": "nodemon"? - Ani
抱歉,没有起作用,应用程序运行但不会在任何断点处暂停 :'( - Ani

1

我正在寻找解决同样问题的方法,并偶然发现了这个问题,截至2022年7月1日,这似乎是最佳方式。使用VSCode中的自动附加功能。

我按照这里的文章进行操作,重新启动了IDE,在代码中设置了断点,然后运行了我的代码:

nodemon app.js

希望一切按预期正确运行。

因此,流程如下:

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

1
我对所有提出的答案都有问题,因为我的MVSC工作区不是直接包含package.json文件的文件夹。因此,我在Ridham Tarpara的答案中添加了一些内容(这里)。 为了使其适用于这种类型的工作区(我的package.json文件位于server目录中)

我的工作区

您需要在工作区的.vscode文件夹中创建一个.launch.json文件。

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "nodemon",
      "runtimeArgs": ["--prefix", "${workspaceRoot}/server", "run", "debug"],
      "runtimeExecutable": "npm",
      "program": "${workspaceRoot}/server/",
      "restart": true,
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen"
    }
  ]
}

关键是要通过使用--prefix参数来指定npm的位置,该位置定义了“debug”命令的package.json文件。然后,在命令的末尾启动这种命令npm --prefix path/to/dir/containing/npm/package run debug
然后,这是我的package.json文件,以完全使用TypeScript运行nodemon。
{
  ...
  "scripts": {
    "start": "tsc && nodemon server",
    "debug": "tsc && nodemon --watch 'server/lib/**' --ext 'ts,json' --exec 'ts-node server.ts'",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接