By Fabian Jakobs


2009-12-15 22:50:07 8 Comments

How do I debug a Node.js server application?

Right now I'm mostly using alert debugging with print statements like this:

sys.puts(sys.inspect(someVariable));

There must be a better way to debug. I know that Google Chrome has a command-line debugger. Is this debugger available for Node.js as well?

30 comments

@Panayiotis Georgiou 2019-01-21 20:07:18

Chrome dev tools it’s an easy way to start debugging your client-side code. Here are the steps on what you need to Debug node app using chrome dev tools. check for more details here

DEBUG NODE APP USING CHROME DEV TOOLS

@Mukesh 2018-12-11 19:52:44

ndb is an improved debugging experience for Node.js, enabled by Chrome DevTools

https://github.com/GoogleChromeLabs/ndb

@Doron Segal 2014-03-12 05:10:29

My original response was couple of years ago pre visual studio.

So, Using GOOD by hapi is a great logging package but for debugging use visual studio.

original response (some long time ago): I would use GOOD by Walmart Labs. It will do the job, and it's very flexible:

var hapi = require('hapi');
var good = require('good');
var server = hapi.createServer('localhost', 5000,{});
server.route({SOME ROUTE HERE});
server.start();

var options = {
subscribers: {
    'console':               ['ops', 'request', 'log', 'error'],
    'http://localhost/logs': ['log']
    }
};
server.pack.require('good', options, function (err) {

    if (!err) {
        console.log('Plugin loaded successfully');
    }
});

@Adam Lear 2014-03-31 06:36:38

Can you elaborate on how you use this to debug node.js? Thanks!

@Doron Segal 2014-04-02 23:19:26

yeah, here's an example: var hapi = require('hapi'); var good = require('good'); var server = hapi.createServer('localhost', 5000,{}); server.route({SOME ROUTE HERE}); server.start(); var options = { subscribers: { 'console': ['ops', 'request', 'log', 'error'], 'localhost/logs': ['log'] } }; server.pack.require('good', options, function (err) { if (!err) { console.log('Plugin loaded successfully'); } });

@Jonathan 2014-08-07 15:58:41

@DoronSegal It would be a lot easier to read this if you added it to the answer.

@Doron Segal 2014-08-09 22:33:35

Sorry about it, feel free to ping on github if you guys have any questions related to node.

@hans 2015-09-09 00:10:11

the link is dead ...

@Shivam 2018-12-04 23:41:09

Good is not for debugging. Its a hapi js plugging to provide interaction with various events generated by the hapi server.

@Doron Segal 2018-12-06 18:56:23

@shivam you are right I wrote this post almost 5 years ago (today Dec, 2018) If you need to debug a node app use vscode with debugger

@babidi 2018-06-04 12:21:56

Using Chrome Version 67.0.3396.62(+)

  1. Run node app

node --inspect-brk=0.0.0.0:9229 server.js(server js filename)

  1. Browse your app in chrome e.g. "localhost:port"
  2. Open DevTools.
  3. Click the the node icon beside the responsive device icon.

enter image description here

There will be another DevTools window that will pop out specifically for debugging node app.

enter image description here

@Oleksii Trekhleb 2018-09-20 11:20:42

You may use pure Node.js and debug the application in the console if you wish.

For example let's create a dummy debug.js file that we want to debug and put breakpoints in it (debugger statement):

let a = 5;
debugger;

a *= 2;
debugger;

let b = 10;
debugger;

let c = a + b;
debugger;

console.log(c);

Then you may run this file for debugging using inspect command:

node inspect debug.js

This will launch the debugger in the console and you'll se the output that is similar to:

< Debugger listening on ws://127.0.0.1:9229/6da25f21-63a0-480d-b128-83a792b516fc
< For help, see: https://nodejs.org/en/docs/inspector
< Debugger attached.
Break on start in debug.js:1
> 1 (function (exports, require, module, __filename, __dirname) { let a = 5;
  2 debugger;
  3

You may notice here that file execution has been stopped at first line. From this moment you may go through the file step by step using following commands (hot-keys):

  • cont to continue,
  • next to go to the next breakpoint,
  • in to step in,
  • out to step out
  • pause to pause it

Let's type cont several times and see how we get from breakpoint to breakpoint:

debug> next
break in misc/debug.js:1
> 1 (function (exports, require, module, __filename, __dirname) { let a = 5;
  2 debugger;
  3
debug> next
break in misc/debug.js:2
  1 (function (exports, require, module, __filename, __dirname) { let a = 5;
> 2 debugger;
  3
  4 a *= 2;
debug> next
break in misc/debug.js:4
  2 debugger;
  3
> 4 a *= 2;
  5 debugger;
  6

What we may do now is we may check the variable values at this point by writing repl command. This will allow you to write variable name and see its value:

debug> repl
Press Ctrl + C to leave debug repl
> a
5
> b
undefined
> c
undefined
>

You may see that we have a = 5 at this moment and b and c are undefined.

Of course for more complex debugging you may want to use some external tools (IDE, browser). You may read more here.

@Fabian Jakobs 2010-03-29 08:57:06

The V8 debugger released as part of the Google Chrome Developer Tools can be used to debug Node.js scripts. A detailed explanation of how this works can be found in the Node.js GitHub wiki.

@balupton 2011-05-19 20:35:27

I'm interested, after the presentation at Google IO that Paul Irish and Pavel did is it now possible to debug node.js straight to Chrome Developer Tools without the need for eclipse?

@amateur barista 2012-01-06 16:40:42

+1 Worked very well for me. Using a fresh Eclipse 3.x, x64 version on Mac OS X. The installation instructions are well written as well. Thank you.

@Paul Verest 2013-06-16 15:53:56

Also comes within Nodeclipse nodeclipse.org (with some Node.js related bugs fixed)

@rocky 2015-05-18 22:04:20

My entry into this arena is trepanjs (npmjs.com/package/trepanjs). It has all of the goodness of the node debugger, but conforms better to gdb. It also has more features and commands like syntax highlighting, more extensive online help, and smarter evaluation. See github.com/rocky/trepanjs/wiki/Cool-things for some of its cool features.

@T.J. Crowder 2016-04-13 14:03:06

Sadly the explanation seems not to exist on the new wiki page.

@zeronone 2016-07-05 02:25:35

The feature is currently available in the nightly versions. Check out here for instructions: https://medium.com/@paul_irish/debugging-node-js-nightlies-w‌​ith-chrome-devtools-‌​7c4a1b95ae27#.fitvua‌​umt

@akatran 2018-09-29 09:38:20

Does not work with Netbeans! As node.js changed the option from --debug[-brk] to --inspect[-brk] the only workaround was to add a npm script for quick debugging. Have in package.json something like: "scripts": { "debug": "node --inspect-brk=9292 main.js" }

@Mr. Raj Kale 2018-04-05 06:28:46

There are may ways to debug Node.JS application as follows:

1) Install devtool and start application with it

npm install devtool -g --save
devtool server.js

this will open in chrome developer mode so you can put a debugger point and test.

2) debug with node-inspector

node-inspector

3) debug with --debug

node --debug app.js 

@Zahirul Haque 2018-03-24 01:51:59

Use this commands

DEBUG_LEVEL=all node file.js
DEBUG=* node file.js
node file.js --inspect

@Rahul Kumar 2018-02-09 19:05:32

Start your node process with --inspect flag.

node --inspect index.js

and then Open chrome://inspect in chrome. Click the "Open dedicated DevTools for Node" link or install this chrome extension for easily opening chrome DevTools.

For more info refer to this link

@Surendra Parchuru 2017-10-15 10:02:20

Visual Studio Code will work for us in debugging.

@Philip O'Brien 2015-09-15 15:33:22

A lot of great answers here, but I'd like to add my view (based on how my approach evolved)

Debug Logs

Let's face it, we all love a good console.log('Uh oh, if you reached here, you better run.') and sometimes that works great, so if you're reticent to move too far away from it at least add some bling to your logs with Visionmedia's debug.

Interactive Debugging

As handy as console logging can be, to debug professionally you need to roll up your sleeves and get stuck in. Set breakpoints, step through your code, inspect scopes and variables to see what's causing that weird behaviour. As others have mentioned, node-inspector really is the bees-knees. It does everything you can do with the built-in debugger, but using that familiar Chrome DevTools interface. If, like me, you use Webstorm, then here is a handy guide to debugging from there.

Stack Traces

By default, we can't trace a series of operations across different cycles of the event loop (ticks). To get around this have a look at longjohn (but not in production!).

Memory Leaks

With Node.js we can have a server process expected to stay up for considerable time. What do you do if you think it has sprung some nasty leaks? Use heapdump and Chrome DevTools to compare some snapshots and see what's changing.


For some useful articles, check out

If you feel like watching a video(s) then

Whatever path you choose, just be sure you understand how you are debugging

enter image description here

It is a painful thing
To look at your own trouble and know
That you yourself and no one else has made it

Sophocles, Ajax

@Alister 2016-09-14 14:51:34

Node has its own built in GUI debugger as of version 6.3 (using Chrome's DevTools)

Nodes builtin GUI debugger

Simply pass the inspector flag and you'll be provided with a URL to the inspector:

node --inspect server.js

You can also break on the first line by passing --inspect-brk instead.

To open a Chrome window automatically, use the inspect-process module.

# install inspect-process globally
npm install -g inspect-process

# start the debugger with inspect
inspect script.js

@Jarid R. Margolin 2016-11-17 22:30:06

Not to discount the steps above, but just to share... I attempted to create a wrapper that is slightly more robust, as well as easier to install. See: github.com/jaridmargolin/inspect-process

@gregers 2016-12-13 10:31:04

@JaridR.Margolin Nice. I updated the answer to use that instead. A lot easier to setup and works better :)

@LOAS 2017-01-02 10:44:36

This answer is currently at the bottom and it's the only one that has actually worked for me. This is flipping awesome!

@MalcolmOcean 2017-02-27 01:42:08

For those using nodemon (if you're not, look it up!), use nodemon --inspect and then this tool to automatically open a new Chrome window: chrome.google.com/webstore/detail/nim-node-inspector-manage/‌​…

@RoccoB 2017-03-23 18:15:51

In case it helps anyone, I threw up a video explaining this process at youtu.be/rtZKUnks6jI.

@Pieter Meiresone 2017-09-10 06:30:57

Where did you got the dark theme for the chrome developer tools?

@Mike Post 2017-11-11 14:09:54

For node 6.x, use node --inspect --debug-brk server.js to automatically stop on the first line.

@Michael 2017-12-07 16:56:38

I am trying to use this, but I can't figure out how to inspect the state of my app to determine why unexpected behavior is happening. how do i access the variables of the main app I started, e.g. server.js?

@cmd 2017-01-21 06:13:29

There are many possibilities...

Debug support is often implemented using the v8 Debugging Protocol or the newer Chrome Debugging Protocol.

@yojimbo87 2011-03-11 19:29:53

There is built-in command line debugger client within Node.js. Cloud 9 IDE have also pretty nice (visual) debugger.

@Teoman shipahi 2016-01-08 15:40:46

Cloud 9 is way to go for me, especially gives freedom of code anywhere option without carrying my laptop.

@Shreyas 2016-02-19 10:21:40

Visual Studio Code will be my choice for debugging. No overhead of installing any tools or npm install stuff. Just set the starting point of your app in package.json and VSCode will automatically create a configuration file inside your solution. It's build on Electron, on which editors like Atom are built.

VS Code gives similar debugging experience as you might have had in other IDEs like VS, Eclipse, etc.

enter image description here enter image description here

@calbertts 2017-05-24 21:48:34

It's cool but it has lag. That's why I do prefer Sublime ever.

@Syed Faizan 2017-10-27 10:35:23

but sublime doesn't have a debugger,and i think VS code is pretty fast too

@elboletaire 2018-03-19 13:22:05

I've a sublime license since 5 years ago. Since a few months ago I don't even install Sublime Text, just vscode. Out of the box has a lot of tools which I miss in Sublime (like the integrated terminal..).

@carkod 2018-06-18 14:55:46

always asking me for a config folder, it doesn't work out of the box

@OneMoreQuestion 2016-07-25 19:13:43

Use Webstorm! It's perfect for debugging Node.js applications. It has a built-in debugger. Check out the docs here: https://www.jetbrains.com/help/webstorm/2016.1/running-and-debugging-node-js.html

@balupton 2013-05-12 21:37:33

Debugging

Profiling

  1. node --prof ./app.js
  2. node --prof-process ./the-generated-log-file

Heapdumps

Flamegraphs

Tracing

Logging

Libraries that output debugging information

Libraries that enhance stack trace information

Benchmarking

Other

Legacy

These use to work but are no longer maintained or no longer applicable to modern node versions.

@reallynice 2013-10-25 12:28:29

About Nodetime: for those who don't want to send their data to nodetime servers there's a local "alternative" (it's still based on nodetime), the look module, as pointed out in stackoverflow.com/questions/12864221/nodejs-memory-profiling

@Farid Nouri Neshat 2014-05-26 10:15:33

falme graphs are already in chrome developers tools.

@shacharz 2014-07-20 12:09:51

I don't find the cpu reports from nodetime very helpful: 1. I just get a tree of methods, with no 'self' time. 2. Seems like the tree branches are trimmed below a certain number of precentage. Those 2 makes it very difficult to undestand where the cpu spends most of its time.

@Stepan Yakovenko 2014-09-08 12:45:30

npm install -g profiler complains about missing python on windows 7. I tried to set python=C:\Python34\, but this gives a crash.

@Stepan Yakovenko 2014-09-08 12:47:36

The only profiler working out of the box is nodetime. But its cpu profiling stacktrace is unusable (it doesn't give enough details). Nodejs tools 4 msvc 2012 also have profiler, but it also has reported critical unfixed bug...

@Dan Abramov 2015-01-09 01:07:30

The only profiler that worked for me was nprof + v8.log from node --prof.

@bgse 2015-10-20 02:36:33

See the answer @hans posted below, should probably include Visual Studio Code here.

@Luciano Mammino 2019-03-01 13:32:15

Definitely worth mentioning node clinic at this point: github.com/nearform/node-clinic

@Stephan Ahlf 2015-07-19 15:10:04

I wrote a different approach to debug Node.js code which is stable and is extremely simple. It is available at https://github.com/s-a/iron-node.

Enter image description here

An opensource cross-platform visual debugger.

Installation:

npm install iron-node -g;

Debug:

iron-node yourscript.js;

@daralthus 2010-10-15 17:17:02

node-inspector could save the day! Use it from any browser supporting WebSocket. Breakpoints, profiler, livecoding, etc... It is really awesome.

Install it with:

npm install -g node-inspector

Then run:

node-debug app.js

@Jonathan Dumaine 2011-12-05 00:32:04

Wish node-inspector was active. The profiling component needs to get some love.

@Silviu-Marian 2012-06-29 17:30:45

You can use github.com/ketamynx/node-codein instead of node-inspector's console. It can display objects.

@jayarjo 2012-07-23 11:13:59

For me breakpoints do not work in node-inspector. Do they for you guys? Any additional mambo-jumbo to make them work?

@balazs 2012-09-05 12:57:38

It used to work for me, but with node v0.8.3 it doesn't work :(

@WickyNilliams 2012-09-26 15:08:43

@jayarjo is it because your program is exiting before breakpoints can be attached? Have you tried running your code with `node --debug-brk"? This breaks on the first line of the code

@Justin Warkentin 2012-10-20 03:17:49

Unfortunately for me, node-inspector doesn't work with the latest versions of Node.js and it hasn't supported logging to the browser console since v0.1. node-codein was just buggy. So, I wrote my own module to help with debugging by allowing you to dump objects and such out to your web browser console. I thought it may be of use to someone else: node-monkey. Plus it works in both Firefox AND Chrome.

@PeterT 2013-03-21 18:13:47

Since this was such an apparently amazing and popular tool, surely the fact that the original author has admitted they no longer have the resources to maintain it wouldn't be a problem as the open source community could pick it up?

@Juan Lanus 2013-06-01 15:54:14

I'm using node-inspector with node 0.10 and it works as expected. I do it in Ubuntu 13.

@balupton 2013-07-25 15:31:53

Now inspector is now actively maintained by StrongLoop and is working again with the latest version (0.3) yay! Announcement here: blog.strongloop.com/…

@sidonaldson 2013-08-14 13:56:06

if you get an INUSE error try changing the port the inspector runs on: --web-port=8181

@Cihad Turhan 2014-07-05 00:32:56

Debugging both client and server on the same window. What else a web developer wants? This is perfect.

@keithl8041 2014-08-28 23:19:14

I have to echo the comments above and say that this tool is far, FAR better than what I was expecting. Definitely give it a go if you haven't tried it before and don't yet have a proper IDE sorted. I've just picked up Node and this is a great tool - works fine with the latest version under Windows (v0.10.31 as of today).

@Mahn 2015-06-01 11:41:54

Is it possible to attach/deattach this debugger during runtime? I guess not, but it would be handy to debug minor issues in production apps without taking them down or running them under the debugger constantly.

@Jacob McKay 2015-07-13 19:15:09

For most people asking this question, including the OP, this answer should be the accepted answer. It is an outstanding alternative to "alert-debugging" and I've used it a crap-ton with much success :D

@Aditya M P 2016-03-04 13:23:45

Yes the rumours about it's death are exaggerated. Those comments ought to be removed because it made me disbelieve the answer and waste some more time.

@Alister 2016-09-15 10:26:08

As of Node 6.3 theres a built in node inspector, please see my answer for details...

@Web Developer 2017-03-11 15:37:16

Thanks for good posting. I tried same but have one error now. NodeInspector Chrome console shows me one error Error: No NativeModule in target scope Nodeinspector load all my project src in Chrome. What should I do?

@ThisClark 2017-06-04 00:31:02

"Since version 6.3, Node.js provides a buit-in DevTools-based debugger which mostly deprecates Node Inspector, see e.g. this blog post to get started. The built-in debugger is developed directly by the V8/Chromium team and provides certain advanced features (e.g. long/async stack traces) that are too difficult to implement in Node Inspector." - says the node inspector repo

@Sergey Brunov 2015-11-24 08:26:37

The NetBeans IDE has had Node.js support since version 8.1:

<...>

New Feature Highlights

Node.js Application Development

  • New Node.js project wizard
  • New Node.js Express wizard
  • Enhanced JavaScript Editor
  • New support for running Node.js applications
  • New support for debugging Node.js applications.

<...>

Additional references:

  1. NetBeans Wiki / NewAndNoteworthyNB81.
  2. Node.js Express App in NetBeans IDE, Geertjan-Oracle.

@hans 2015-09-09 00:08:22

Visual Studio Code has really nice Node.js debugging support. It is free, open source and cross-platform and runs on Linux, OS X and Windows.

You can even debug grunt and gulp tasks, should you need to...

@bgse 2015-10-20 02:35:59

Starting from Visual Studio Code 8.0 the debugging support for OSX and Linux got really good.

@dashambles 2016-02-07 13:33:01

After spending a whole evening getting node-inspector and strongloop to function under windows (Visual Studio Community, downgrade to npm 2, installing python, env variables, use cmd not babun / cygwin etc. etc.) and then playing with this for an hour, I have to say this is the best option at least in windows and possibly in general (if you don't have webstorn)

@Gerold Meisinger 2015-05-14 18:20:39

A quick-and-dirty way to debug small Node.js scripts with your favorite browser debugger would be to use browserify. Note that this approach doesn't work with any applications which require native I/O libraries, but it is good enough for most small scripts.

$ npm install -g browserify

Now move all your var x = requires('x') calls into a requires.js file and run:

$ browserify requires.js -s window -o bundle.js

(The downside here is that you either have to move or comment the requires in all your files.)

Include the bundle.js in an HTML file like so:

<script type="text/javascript" src="bundle.js"></script>

Now load the file in your browser and press F12 and viola: debug in browser.

@Uchiha Itachi 2015-03-30 04:04:35

If you are using the Atom IDE, you can install the node-debugger package.

@Alex 2014-02-05 01:27:05

@Paul Verest 2014-01-02 05:24:39

There is the new open-source Nodeclipse project (as a Eclipse plugin or Enide Studio):

http://www.nodeclipse.org/img/Nodeclipse-1-debugging.png

Nodeclipse became #1 in Eclipse Top 10 NEW Plugins for 2013. It uses a modified V8 debugger (from Google Chrome Developer Tools for Java).

Nodeclipse is free open-source software released at the start of every month.

@卢声远 Shengyuan Lu 2015-08-05 03:34:42

IntelliJ works wonderfully for Node.js.

In addition, IntelliJ supports 'Code Assistance' well.

@BlaineSch 2014-12-09 15:22:41

I created a neat little tool called pry.js that can help you out.

Put a simple statement somewhere in your code, run your script normally and node will halt the current thread giving you access to all your variables and functions. View/edit/delete them at will!

pry = require('pryjs')

class FizzBuzz

  run: ->
    for i in [1..100]
      output = ''
      eval(pry.it) # magic
      output += "Fizz" if i % 3 is 0
      output += "Buzz" if i % 5 is 0
      console.log output || i

  bar: ->
    10

fizz = new FizzBuzz()
fizz.run()

@John81 2014-05-02 12:30:11

Node.js Tools for Visual Studio 2012 or 2013 includes a debugger. The overview here states "Node.js Tools for Visual Studio includes complete support for debugging node apps.". Being new to Node.js, but having a background in .NET, I've found this add in to be a great way to debug Node.js applications.

@Shaheen Ghiassy 2013-04-29 01:20:36

Assuming you have node-inspector installed on your computer (if not, just type 'npm install -g node-inspector') you just have to run:

node-inspector & node --debug-brk scriptFileName.js

And paste the URI from the command line into a WebKit (Chrome / Safari) browser.

@Dan Dascalescu 2014-02-12 01:46:46

node-inspector was already mentioned; maybe delete this answer?

@isNaN1247 2012-05-03 14:42:13

I personally use JetBrains WebStorm as it's the only JavaScript IDE that I've found which is great for both frontend and backend JavaScript.

It works on multiple OS's and has Node.js debugging built-in (as well as a ton of other stuff](http://www.jetbrains.com/webstorm/features/index.html).

My only 'issues'/wishlist items are were:

  1. It seems to be more resource hungry on Mac than Windows It no longer seems an issue in version 6.
  2. It would be nice if it had Snippet support (like those of Sublime Text 2 - i.e. type 'fun' and tap 'tab' to put in a function. See @WickyNilliams comment below - With Live Templates you also have snippet support.

@WickyNilliams 2012-09-26 15:12:35

webstorm does have snippet support BTW ;-) though they're known as "Live Templates" instead of snippets.

@Josh Liptzin 2014-06-11 19:45:31

If you just want to debug a node.js app and already have an Intellij IDEA license you can just install the node.js plugin without having to buy the WebStorm license. Setting up a run/debug config is very easy once the plugin is installed.

Related Questions

Sponsored Content

86 Answered Questions

[SOLVED] How do JavaScript closures work?

29 Answered Questions

76 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5594795 View
  • 6935 Score
  • 76 Answer
  • Tags:   javascript arrays

16 Answered Questions

[SOLVED] How to exit in Node.js

  • 2011-03-10 21:30:05
  • Bryan Field
  • 729340 View
  • 1562 Score
  • 16 Answer
  • Tags:   node.js

47 Answered Questions

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

53 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

17 Answered Questions

[SOLVED] How to decide when to use Node.js?

8 Answered Questions

[SOLVED] Debugging with command-line parameters in Visual Studio

14 Answered Questions

[SOLVED] How do I print debug messages in the Google Chrome JavaScript Console?

Sponsored Content