DEV Community

Cover image for Debugging Node.js like a PRO
Mihail
Mihail

Posted on

Debugging Node.js like a PRO

If you opened this post, you want to unlock the ultimate power of debugging node.js apps. I think you will agree that the console.log is still the king. It's time you close the article now. Or not...

The other day, I was trying to debug why a migration takes forever to run. Unfortunately, it was using a 3rd party package to do that, so I did not have direct access to the codebase(except by going to the node_modules folder or GitHub). But even if I can open the code, of course, it's tough to understand it.

If there could be a way to hook into the code execution...

Wait, there actually is. Just follow the official guide for Debugging in node, and you're done. However, for some reason(I bet it has something to do with the worker_threads or some child process) it didn't worked in my case.

Another option would be to use the .vscode/launch.json file, but I always find it painful to create and read.

Can there be an even easier way to run debug mode for node?

The answer is simple: YES. And this was the day when I found the Debug: Toggle Auto Attach command in VS Code(my current editor of choice, as I can't finish my Neovim config 😀). Just press Cmd(or Ctrl)+Shift+P, paste Debug: Toggle Auto Attach and choose from one of the available modes: Always, Smart, Only With Flag, Disabled. You can read more about each option here.

After selecting the option, all you have to do now is to restart your terminal in VS Code, add the breakpoint in your code, run the node script(via node, npm, yarn, etc) and focus on identifying and solving the problem.

For my case, I used the Always option, as I wanted to have the debugger running for all the node processes that run in my terminal. This way, I was able to find and report the problem of why the migration ran slow(fetched too many rows because of a specific config option, which should not be the case). Once I was done, I chose Disabled option and got back to the king of debugging, console.log.

I hope you enjoyed the post and it was somewhat helpful.

Top comments (0)