1639

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?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Fabian Jakobs
  • 27,222
  • 7
  • 38
  • 37
  • 3
    You can use [Locus](https://github.com/alidavut/locus) for command line injection. – Ali Davut Dec 12 '13 at 19:44
  • 5
    If you want to debug with the traditional IDE appoach, use vscode use vscode https://www.youtube.com/watch?v=egBJ0cd0GLM – jw56578 Sep 20 '16 at 03:09
  • 4
    I have found this article very interesting, and it works for me just fine: [**Debugging Node.js with Chrome DevTools**](https://medium.com/@paul_irish/debugging-node-js-nightlies-with-chrome-devtools-7c4a1b95ae27#.68uvlrpco). Hope it helps :) – Timbergus Feb 15 '17 at 09:50
  • 2
    "alert debugging" :) – The Red Pea Jun 01 '17 at 16:32
  • Keep in mind that you need to run nod with `--inspect-brk` INSTEAD OF `--inspect` if you want to debug the actual server code at load time. See https://stackoverflow.com/questions/59596138 – Jorge Orpinel Jan 05 '20 at 00:48
  • Check this blog: https://medium.com/@paul_irish/debugging-node-js-nightlies-with-chrome-devtools-7c4a1b95ae27 – AbiSivam Jan 08 '20 at 07:12

40 Answers40

1284

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
daralthus
  • 13,426
  • 2
  • 14
  • 13
  • 15
    Wish node-inspector was active. The profiling component needs to get some love. – Jonathan Dumaine Dec 05 '11 at 00:32
  • 1
    You can use https://github.com/ketamynx/node-codein instead of node-inspector's console. It can display objects. – Silviu-Marian Jun 29 '12 at 17:30
  • For me breakpoints do not work in node-inspector. Do they for you guys? Any additional mambo-jumbo to make them work? – jayarjo Jul 23 '12 at 11:13
  • It used to work for me, but with node v0.8.3 it doesn't work :( – balazs Sep 05 '12 at 12:57
  • 1
    @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 – WickyNilliams Sep 26 '12 at 15:08
  • 14
    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](https://github.com/jwarkentin/node-monkey). Plus it works in both Firefox AND Chrome. – Justin Warkentin Oct 20 '12 at 03:17
  • 7
    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? – PeterT Mar 21 '13 at 18:13
  • 1
    I'm using node-inspector with node 0.10 and it works as expected. I do it in Ubuntu 13. – Juan Lanus Jun 01 '13 at 15:54
  • 34
    Now inspector is now actively maintained by StrongLoop and is working again with the latest version (0.3) yay! Announcement here: http://blog.strongloop.com/announcing-a-new-and-improved-node-js-debugger/ – balupton Jul 25 '13 at 15:31
  • if you get an INUSE error try changing the port the inspector runs on: --web-port=8181 – sidonaldson Aug 14 '13 at 13:56
  • 1
    Debugging both client and server on the same window. What else a web developer wants? This is perfect. – Cihad Turhan Jul 05 '14 at 00:32
  • 1
    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). – keithl8041 Aug 28 '14 at 23:19
  • 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. – Mahn Jun 01 '15 at 11:41
  • 3
    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 – Jacob McKay Jul 13 '15 at 19:15
  • 1
    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. – Aditya M P Mar 04 '16 at 13:23
  • 3
    As of Node 6.3 theres a built in node inspector, please see my answer for details... – Alister Sep 15 '16 at 10:26
  • 25
    *"Since version 6.3, Node.js provides a buit-in DevTools-based debugger which mostly deprecates Node Inspector, see e.g. [this blog post](https://medium.com/@paul_irish/debugging-node-js-nightlies-with-chrome-devtools-7c4a1b95ae27) 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 – ThisClark Jun 04 '17 at 00:31
768

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.

codemeasandwich
  • 1,260
  • 1
  • 13
  • 23
balupton
  • 42,415
  • 27
  • 116
  • 167
  • 8
    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 http://stackoverflow.com/questions/12864221/nodejs-memory-profiling – reallynice Oct 25 '13 at 12:28
  • 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. – shacharz Jul 20 '14 at 12:09
  • 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 Sep 08 '14 at 12:45
  • 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... – Stepan Yakovenko Sep 08 '14 at 12:47
  • The only profiler that worked for me was `nprof` + `v8.log` from `node --prof`. – Dan Abramov Jan 09 '15 at 01:07
  • See the answer @hans posted below, should probably include Visual Studio Code here. – bgse Oct 20 '15 at 02:36
  • Definitely worth mentioning node clinic at this point: https://github.com/nearform/node-clinic – Luciano Mammino Mar 01 '19 at 13:32
  • Keep in mind that you need to run nod with `--inspect-brk` INSTEAD OF `--inspect` if you want to debug the actual server code at load time. See https://stackoverflow.com/questions/59596138 – Jorge Orpinel Jan 05 '20 at 00:50
262

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.

d4nyll
  • 9,170
  • 5
  • 43
  • 59
Fabian Jakobs
  • 27,222
  • 7
  • 38
  • 37
  • 12
    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? – balupton May 19 '11 at 20:35
  • +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. – amateur barista Jan 06 '12 at 16:40
  • Also comes within Nodeclipse http://www.nodeclipse.org/ (with some Node.js related bugs fixed) – Paul Verest Jun 16 '13 at 15:53
  • My entry into this arena is trepanjs (https://www.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 https://github.com/rocky/trepanjs/wiki/Cool-things for some of its cool features. – rocky May 18 '15 at 22:04
  • Sadly the explanation seems not to exist on the new wiki page. – T.J. Crowder Apr 13 '16 at 14:03
  • 1
    The feature is currently available in the nightly versions. Check out here for instructions: `https://medium.com/@paul_irish/debugging-node-js-nightlies-with-chrome-devtools-7c4a1b95ae27#.fitvuaumt` – zeronone Jul 05 '16 at 02:25
  • 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" } – akatran Sep 29 '18 at 09:38
202

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.

Alister
  • 21,405
  • 8
  • 36
  • 31
  • 2
    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: https://github.com/jaridmargolin/inspect-process – Jarid R. Margolin Nov 17 '16 at 22:30
  • 1
    @JaridR.Margolin Nice. I updated the answer to use that instead. A lot easier to setup and works better :) – gregers Dec 13 '16 at 10:31
  • 2
    This answer is currently at the bottom and it's the only one that has actually worked for me. This is flipping awesome! – LOAS Jan 02 '17 at 10:44
  • 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: https://chrome.google.com/webstore/detail/nim-node-inspector-manage/gnhhdgbaldcilmgcpfddgdbkhjohddkj/related – MalcolmOcean Feb 27 '17 at 01:42
  • 3
    In case it helps anyone, I threw up a video explaining this process at https://youtu.be/rtZKUnks6jI. – RoccoB Mar 23 '17 at 18:15
  • 2
    Where did you got the dark theme for the chrome developer tools? – Pieter Meiresone Sep 10 '17 at 06:30
  • 1
    For node 6.x, use `node --inspect --debug-brk server.js` to automatically stop on the first line. – Mike Post Nov 11 '17 at 14:09
  • Keep in mind that you need to run nod with `--inspect-brk` INSTEAD OF `--inspect` if you want to debug the actual server code at load time. See https://stackoverflow.com/questions/59596138 – Jorge Orpinel Jan 05 '20 at 00:49
96

Node.js version 0.3.4+ has built-in debugging support.

node debug script.js

Manual: http://nodejs.org/api/debugger.html

Salman von Abbas
  • 21,808
  • 8
  • 64
  • 56
JulianW
  • 1,007
  • 7
  • 3
  • 1
    Do you have any links to documentation of how to use it? – Fabian Jakobs Jan 16 '11 at 12:17
  • 2
    I don't have any docs. just updated to v0.3.5. put a line "debugger;" in your code which will act as break point. It works like ndb / gdb. after you do "node debug script.js" type help. u will see the command it support. p = print, l = list... so you don't need to type the full world – JulianW Jan 20 '11 at 23:59
  • 2
    Note, under windows it's "node.exe --debug myscript.js" but it still don't work. – Marc Sep 06 '11 at 12:13
  • 6
    You probably have to change `--debug` to `debug` without the dashes. That's how I finally got it to work. It's confusing that `--debug` and `debug` do two different things. – benekastah Oct 07 '11 at 05:55
  • How do you get the program to actually run? "r -> `app is already running...`", when i try to continue and i run into a statement that is trying to get input it drops me back at the debug prompt instead of letting me enter the input that is required. – Michael Jul 11 '16 at 23:22
  • debug has been deprecated. you have to use `node inspect script.js` now – Isaac Pak Sep 24 '18 at 04:57
73

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

Shreyas
  • 1,817
  • 14
  • 32
  • It's cool but it has lag. That's why I do prefer Sublime ever. – calbertts May 24 '17 at 21:48
  • 3
    but sublime doesn't have a debugger,and i think VS code is pretty fast too – Syed Faizan Oct 27 '17 at 10:35
  • 1
    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..). – elboletaire Mar 19 '18 at 13:22
  • always asking me for a config folder, it doesn't work out of the box – carkod Jun 18 '18 at 14:55
  • @carkod enable vs code _**auto attach**_ preference and use the vs code _**terminal**_ to start your script, ex node --inspect file-name.js – Vipul Dessai Dec 25 '19 at 11:16
59

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.
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
isNaN1247
  • 17,115
  • 12
  • 66
  • 114
  • 10
    webstorm does have snippet support BTW ;-) though they're known as "Live Templates" instead of snippets. – WickyNilliams Sep 26 '12 at 15:12
  • 3
    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. – Josh Liptzin Jun 11 '14 at 19:45
43

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

Philip O'Brien
  • 3,734
  • 7
  • 39
  • 91
42

Theseus is a project by Adobe research which lets you debug your Node.js code in their Open Source editor Brackets. It has some interesting features like real-time code coverage, retroactive inspection, asynchronous call tree.

screenshot

Sindre Sorhus
  • 62,754
  • 35
  • 155
  • 217
  • this is pretty cool, still don't know what's Backtrace for tho – misaxi Feb 18 '14 at 23:33
  • I'm currently loving Theseus, but I still have some problems where I need to set a breakpoint and trace through. I'm currently having to kill my app, start node with --debug, trace trhough and then start the app with node-theseus. Is it possible to use Theseus with breakpoints? I've tried searching around the GitHub page, StackOverflow and forums, but with no luck so far. Am I missing something? – Eugene Jul 15 '15 at 01:21
26

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
John81
  • 2,718
  • 5
  • 31
  • 54
24

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...

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
hans
  • 971
  • 9
  • 14
  • 1
    Starting from Visual Studio Code 8.0 the debugging support for OSX and Linux got really good. – bgse Oct 20 '15 at 02:35
  • 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) – dashambles Feb 07 '16 at 13:33
22

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;

Community
  • 1
  • 1
Stephan Ahlf
  • 2,839
  • 3
  • 31
  • 65
16

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Uchiha Itachi
  • 691
  • 2
  • 9
  • 14
15

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

babidi
  • 456
  • 5
  • 6
14

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!

var 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()
keen
  • 756
  • 9
  • 10
Baylee
  • 177
  • 1
  • 6
12

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

keen
  • 756
  • 9
  • 10
yojimbo87
  • 59,764
  • 22
  • 119
  • 130
11

I put together a short Node.js debugging primer on using the node-inspector for those who aren't sure where to get started.

Josh Habdas
  • 6,370
  • 2
  • 53
  • 55
11

Visual Studio Code will work for us in debugging.

Surendra Parchuru
  • 853
  • 1
  • 11
  • 17
8

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Shaheen Ghiassy
  • 6,630
  • 2
  • 36
  • 39
8

Just for completeness:

The PyCharm 3.0 + Node.js Plugin offers an awesome development + run + debug experience.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Alex
  • 1,917
  • 1
  • 15
  • 31
8

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

OneMoreQuestion
  • 1,544
  • 2
  • 19
  • 43
8

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

Rahul Kumar
  • 4,500
  • 5
  • 33
  • 43
8

If you need a powerful logging library for Node.js, Tracer https://github.com/baryon/tracer is a better choice.

It outputs log messages with a timestamp, file name, method name, line number, path or call stack, support color console, and support database, file, stream transport easily. I am the author.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Baryon Lee
  • 1,019
  • 11
  • 11
5

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

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.

Glorfindel
  • 19,729
  • 13
  • 67
  • 91
Paul Verest
  • 51,779
  • 39
  • 174
  • 288
5

IntelliJ works wonderfully for Node.js.

In addition, IntelliJ supports 'Code Assistance' well.

卢声远 Shengyuan Lu
  • 29,208
  • 21
  • 78
  • 123
5

There are many possibilities...

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

cmd
  • 10,795
  • 6
  • 47
  • 59
4

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.
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Sergey Brunov
  • 11,755
  • 7
  • 39
  • 71
4

Use this commands

DEBUG_LEVEL=all node file.js
DEBUG=* node file.js
node file.js --inspect
Zahirul Haque
  • 1,106
  • 12
  • 20
4

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

https://github.com/GoogleChromeLabs/ndb

Mukesh
  • 1,139
  • 9
  • 24
3
node-debug -p 8888 scriptFileName.js
matt burns
  • 22,440
  • 9
  • 91
  • 102
3

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Gerold Meisinger
  • 4,411
  • 5
  • 22
  • 33
2

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');
    }
});
Doron Segal
  • 1,982
  • 19
  • 21
  • 3
    Can you elaborate on how you use this to debug node.js? Thanks! – Adam Lear Mar 31 '14 at 06:36
  • 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'], 'http://localhost/logs': ['log'] } }; server.pack.require('good', options, function (err) { if (!err) { console.log('Plugin loaded successfully'); } }); – Doron Segal Apr 02 '14 at 23:19
  • @DoronSegal It would be a lot easier to read this if you added it to the answer. – Jonathan Aug 07 '14 at 15:58
  • Sorry about it, feel free to ping on github if you guys have any questions related to node. – Doron Segal Aug 09 '14 at 22:33
  • Good is **not** for debugging. Its a hapi js plugging to provide interaction with various events generated by the hapi server. – Shivam Dec 04 '18 at 23:41
  • @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 – Doron Segal Dec 06 '18 at 18:56
2

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.

Oleksii Trekhleb
  • 1,795
  • 16
  • 21
1

There is a lot of ways to debug but I prefer and I use builtin debugger by node js.

app.js file

var fs = require('fs');

fs.readFile('test.txt', 'utf8', function (err, data) {

debugger;

if (err) throw err;

console.log(data); });

command: node debug app.js

Slim Coder
  • 844
  • 5
  • 14
1

Enable VS Code preference Auto Attach from File -> Preferences -> Settings -> Search for Auto Attach and set it On, open the console (ctrl + *) or from the menu Terminal -> New Terminal, set a breakpoint in your code, type in the command

node --inspect <name of your file>

This will start the debugging and the VS Code will show the Debug menu.

Note: Auto Attach is also very helpful if you are working with node cluster worker threads.

Misha Akopov
  • 9,542
  • 26
  • 54
  • 73
Vipul Dessai
  • 164
  • 2
  • 10
1

Another option not mentioned in other answers is using a tool called Rookout. It's used to debug and get data from both local and remote apps. We use it in our production environment to aggregate data to other services - saves us a lot of headaches and hardcoded logging

  • Please consider adding some explanation and details to your answer. While it might answer the question, just adding some links does not help OP or future community members understand the issue or solution. – hongsy Jan 22 '20 at 09:44
0

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 
Mr. Raj Kale
  • 87
  • 1
  • 7
0

You can try-catch errors:

function yourFunc() {
  try {
      // YOUR CODE HERE
  } catch (err) {
      console.error(err.message + ", " + err.trace);
  }
}

Error message and error trace will give you infomation you need to identify and correct run-time bugs.

LEMUEL ADANE
  • 6,680
  • 14
  • 48
  • 64
0

This method is valid to JS also Node js. It is put debugger word that you want to check. When running your JS or Node js app open the inspect element in the browser. If reach that line execution will pause like the below image.

enter image description here

-3

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

Panayiotis Georgiou
  • 786
  • 1
  • 13
  • 29