2

I am experimenting with different environments for debugging a nodejs application. I am running this application using pm2, with the --watch flag, so that my application restarts when files are changed / saved. Relevant scripts are these:

"start": "node --inspect -r tsconfig-paths/register -r ts-node/register ./src/server.ts",
"launch": "pm2 start pm2.config.js",

And my pm2.config.js looks like this:

module.exports = {
    apps: [
        {
            name: 'myapp',
            script: 'npm',
            args: 'start',
            watch: ['src'],
        },
    ],
};

So far, I have been doing debugging in the chrome node inspector. I'm also using the chrome extension NodeJS Inspector Manager, which is a nice wrapper for the node inspector. It has a nice UI, and you can see there are options for Auto Attach and Auto Resume:

enter image description here

With these enabled, any time I save files in my project, pm2 will restart the application. NiMs automatically detaches and reattaches to the running application, and I have an interactive chrome inspector debugging environment that refreshes through application restart.

I'd like to reproduce this effect within the vscode debugger. I can manually start a debug session that attaches to my application running through pm2. With some help from Debugging With PM2 And Vscode, I'm able to direct the vscode debugger to attach to my application running through pm2. However, when I save files, pm2 restarts the process, and vscode debugger detaches, but does not reattach.

NiMs has a vscode extension, though it doesn't seem to offer the same functionality within vscode as within chrome, as far as I can tell.

Is there a way to set up a vscode debugger to attach to a pm2 process, and automatically restart as the process restarts (on the same debugger port)?

Seth Lutske
  • 9,154
  • 5
  • 29
  • 78

1 Answers1

5

To have vscode debugger re-attach automatically, you can add the flag restart to your configuration:

{
  "name": "Attach to node",
  "type": "node",
  "request": "attach",
  "restart": true,
  "port": 9229
}

source: https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_restarting-debug-sessions-automatically-when-source-is-edited

finrodd
  • 226
  • 1
  • 4
  • 1
    So simple. Thank you, this works! – Seth Lutske Oct 28 '21 at 20:47
  • i searched a long tie for exactly this answer and came acress so many complicated solutions. thank you very much – DerHerrGammler Nov 24 '22 at 20:16
  • alternatively you could use "Auto Attach" built into vsc. doest even need a launch.json file and restarts with the updated code every time you save something to the file. https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_auto-attach – some_groceries Jul 27 '23 at 00:45