Methods to Debug a Node.js Software: Suggestions, Methods and Instruments

Software program growth is complicated and, in some unspecified time in the future, your Node.js software will fail. For those who’re fortunate, your code will crash with an apparent error message. For those who’re unfortunate, your software will stick with it regardless however not generate the outcomes you anticipate. For those who’re actually unfortunate, all the things will work tremendous till the primary person discovers a catastrophic disk-wiping bug.

What’s Debugging?

Debugging is the black artwork of fixing software program defects. Fixing a bug is usually simple — a corrected character or further line of code solves the issue. Discovering that bug is one other matter, and builders can spend many sad hours attempting to find the supply of a problem. Fortuitously, Node.js has some nice instruments to assist hint errors.

Terminology

Debugging has its personal number of obscure jargon, together with the next:

Time period
Clarification
breakpoint
the purpose at which a debugger stops a program so its state may be inspected
debugger
a instrument which provides debugging services resembling operating code line by line to examine inside variable states
function
as within the declare: “it’s not a bug, it’s a function”. All builders say it in some unspecified time in the future throughout their profession
frequency
how usually or underneath what situations a bug will happen
it doesn’t work
the most-often made however least helpful bug report
log level
an instruction to a debugger to point out the worth of a variable at some extent throughout execution
logging
output of runtime data to the console or a file
logic error
this system works however doesn’t act as meant
precedence
the place a bug is allotted on an inventory of deliberate updates
race situation
hard-to-trace bugs dependent the sequence or timing of uncontrollable occasions
refactoring
rewriting code to assist readability and upkeep
regression
re-emergence of a beforehand fastened bug maybe owing to different updates
associated
a bug which is analogous or associated to a different
reproduce
the steps required to trigger the error
RTFM error
person incompetence disguised as a bug report, sometimes adopted by a response to “Learn The Flipping Handbook”
step into
when operating code line by line in a debugger, step into the perform being referred to as
step out
when operating line by line, full execution of the present perform and return to the calling code
step over
when operating line by line, full execution of a command with out stepping right into a perform it calls
severity
the influence of a bug on system. For instance, information loss would usually be thought of extra problematic than a UI concern except the frequency of prevalence could be very low
stack hint
the historic checklist of all features referred to as earlier than the error occurred
syntax error
typographical errors, resembling console.lug()
person error
an error brought on by a person relatively than the applying, however should incur an replace relying on that particular person’s seniority
watch
a variable to look at throughout debugger execution
watchpoint
much like a breakpoint, besides this system is stopped when a variable is ready to a particular worth

Methods to Keep away from Bugs

Bugs can usually be prevented earlier than you check your software …

Use a Good Code Editor

A superb code editor will provide quite a few options together with line numbering, auto-completion, color-coding, bracket matching, formatting, auto-indentation, variable renaming, snippet reuse, object inspection, perform navigation, parameter prompts, refactoring, unreachable code detection, strategies, kind checking, and extra.

Node.js devs are spoiled for selection with free editors resembling VS Code, Atom, and Brackets, in addition to loads of industrial options.

Use a Code Linter

A linter can report code faults resembling syntax errors, poor indentation, undeclared variables, and mismatching brackets earlier than you save and check your code. The favored choices for JavaScript and Node.js embrace ESLint, JSLint, and JSHint.

These are sometimes put in as world Node.js modules so you possibly can run checks from the command line:

eslint myfile.js

Nonetheless, most linters have code editor plugins, resembling ESLint for VS Code and linter-eslint for Atom which verify your code as you kind:

Use Supply Management

A supply management system resembling Git will help safe-guard your code and handle revisions. It turns into simpler to find the place and when a bug was launched and who ought to obtain the blame! On-line repositories resembling GitHub and Bitbucket provide free house and administration instruments.

Undertake an Problem-tracking System

Does a bug exist if nobody is aware of about it? A problem-tracking system is used to report bugs, discover duplicates, doc replica steps, decide severity, calculate priorities, assign builders, file discussions, and observe progress of any fixes.

On-line supply repositories usually provide primary concern monitoring, however devoted options could also be acceptable for bigger groups and tasks.

Use Check-driven Growth

Check-driven Growth (TDD) is a growth course of which inspires builders to jot down code which checks the operation of a perform earlier than it’s written — for instance, is X returned when perform Y is handed enter Z.

Checks may be run because the code is developed to show a perform works and spot any points as additional modifications are made. That mentioned, your checks may have bugs too …

Step Away

It’s tempting to remain up all evening in a futile try to find the supply of a nasty bug. Don’t. Step away and do one thing else. Your mind will subconsciously work on the issue and wake you at 4am with an answer. Even when that doesn’t occur, recent eyes will spot that apparent lacking semicolon.

Node.js Debugging: Surroundings Variables

Surroundings variables which might be set inside the host working system can be utilized to regulate Node.js software settings. The most typical is NODE_ENV, which is usually set to growth when debugging.

Surroundings variables may be set on Linux/macOS:

NODE_ENV=growth

Home windows cmd:

set NODE_ENV=growth

Or Home windows Powershell:

$env:NODE_ENV=”growth”

Internally, an software will allow additional debugging options and messages. For instance:

// is NODE_ENV set to “growth”?
const DEVMODE = (course of.env.NODE_ENV === ‘growth’);

if (DEVMODE)

NODE_DEBUG permits debugging messages utilizing the Node.js util.debuglog (see beneath), but additionally seek the advice of the documentation of your main modules and frameworks to find additional choices.

Be aware that surroundings variables may also be saved to a .env file. For instance:

NODE_ENV=growth
NODE_LOG=./log/debug.log
SERVER_PORT=3000
DB_HOST=localhost
DB_NAME=mydatabase

Then loaded utilizing the dotenv module:

require(‘dotenv’).config();

Node.js Debugging: Command Line Choices

Varied command-line choices may be handed to the node runtime when launching an software. One of the crucial helpful is –trace-warnings, which outputs stack traces for course of warnings (together with deprecations).

Any variety of choices may be set, together with:

–enable-source-maps: allow supply maps (experimental)
–throw-deprecation: throw errors when deprecated options are used
–inspect: activate the V8 inspector (see beneath)

By means of an instance, let’s attempt to log the crypto module’s DEFAULT_ENCODING property, which was deprecated in Node v10:

const crypto = require(‘crypto’);

perform bar()
console.log(crypto.DEFAULT_ENCODING);

perform foo()

foo();

Now run this with the next:

node index.js

We’ll then see this:

buffer
(node:7405) [DEP0091] DeprecationWarning: crypto.DEFAULT_ENCODING is deprecated.

Nonetheless, we are able to additionally do that:

node –trace-warnings index.js

That produces the next:

buffer
(node:7502) [DEP0091] DeprecationWarning: crypto.DEFAULT_ENCODING is deprecated.
at bar (/dwelling/Desktop/index.js:four:22)
at foo (/dwelling/Desktop/index.js:eight:three)
at Object. (/dwelling/Desktop/index.js:11:1)
at Module._compile (inside/modules/cjs/loader.js:1151:30)
at Object.Module._extensions..js (inside/modules/cjs/loader.js:1171:10)
at Module.load (inside/modules/cjs/loader.js:1000:32)
at Operate.Module._load (inside/modules/cjs/loader.js:899:14)
at Operate.executeUserEntryPoint [as runMain] (inside/modules/run_main.js:71:12)
at inside/principal/run_main_module.js:17:47

This tells us that the deprecation warning comes from the code in line four (the console.log assertion), which was executed when the bar perform ran. The bar perform was referred to as by the foo perform on line eight and the foo perform was referred to as on line 11 of our script.

Be aware that the identical choices may also be handed to nodemon.

Console Debugging

One of many best methods to debug an software is to output values to the console throughout execution:

console.log( myVariable );

Few builders delve past this humble debugging command, however they’re lacking out on many extra prospects, together with these:

console.log() accepts an inventory of comma-separated values. For instance:

let x = 123;
console.log(‘x:’, x);
// x: 123

Nonetheless, ES6 destructuring can provide related output with much less typing effort:

console.log();
//

Bigger objects may be output as a condensed string utilizing this:

console.log( JSON.stringify(obj) );

util.examine will format objects for simpler studying, however console.dir() does the onerous be just right for you.

Node.js util.debuglog

The Node.js util module provides a built-in debuglog technique which conditionally writes messages to STDERR:

const util = require(‘util’);
const debuglog = util.debuglog(‘myapp’);

debuglog(‘myapp debug message [%d]’, 123);

When the NODE_DEBUG surroundings variable is ready to myapp (or a wildcard resembling * or my*), messages are displayed within the console:

NODE_DEBUG=myapp node index.js
MYAPP 9876: myapp debug message [123]

Right here, 9876 is the Node.js course of ID.

By default, util.debuglog is silent. For those who have been to run the above script with out setting a NODE_DEBUG variable, nothing can be output to the console. This lets you depart useful debug logging in your code with out cluttering the console for normal use.

Debugging with Log Modules

Third-party logging modules can be found do you have to require extra subtle choices for messaging ranges, verbosity, sorting, file output, profiling, and extra. Widespread choices embrace:

Node.js V8 Inspector

Within the following sections, the pagehit challenge developed in different tutorials is used as an example debugging ideas. You’ll be able to obtain it with:

git clone https://github.com/sitepoint-editors/pagehit-ram

Or you should utilize any of your individual code.

Node.js is a wrapper across the V8 JavaScript engine which incorporates its personal inspector and debugging shopper. To start out, use the examine argument (to not be confused with –inspect) to start out an software:

node examine ./index.js

The debugger will pause on the first line and show a debug> immediate:

< Debugger listening on ws://127.zero.zero.1:9229/6f38abc1-8568-4035-a5d2-dee6cbbf7e44 < For assist, see: https://nodejs.org/en/docs/inspector < Debugger attached. Break on start in index.js:7 5 const 6 // default HTTP port > 7 port = 3000,
eight
9 // Node.js modules
debug>

You’ll be able to step via the applying by getting into:

cont or c: proceed execution
subsequent or n: run the subsequent command
step or s: step right into a perform being referred to as
out or o: step out of a perform and return to the calling command
pause: pause operating code

Different choices embrace:

watching variable values with watch(‘myvar’)
setting breakpoints with the setBreakpoint()/sb() command (it’s normally simpler to insert a debugger; assertion in your code)
restart a script
.exit the debugger (the preliminary . is required)

If this sounds horribly clunky, it’s. Solely use the built-in debugging shopper when there’s completely no different possibility, you’re feeling significantly masochistic, and also you’re not utilizing Home windows (it’s usually problematic).

Node.js Debugging with Chrome

The Node.js inspector (with out the debugger shopper) is began with the –inspect flag:

node –inspect ./index.js

Be aware: nodemon can be utilized as an alternative of node if crucial.

This begins the debugger listening on 127.zero.zero.1:9229, which any native debugging shopper can connect to:

Debugger listening on ws://127.zero.zero.1:9229/20ac75ae-90c5-4db6-af6b-d9d74592572f

For those who’re operating the Node.js software on one other gadget or Docker container, guarantee port 9229 is accessible and grant distant entry utilizing this:

node –inspect=zero.zero.zero.zero:9229 ./index.js

Alternatively, you should utilize –inspect-brk to set a breakpoint on the primary assertion so the applying is paused instantly.

Open Chrome and enter chrome://examine within the deal with bar.

Chrome inspect

Be aware: if the Node.js software does’t seem as a Distant Goal, guarantee Uncover community targets is checked, then click on Configure so as to add the IP deal with and port of the gadget the place the applying is operating.

Click on the Goal’s examine hyperlink to launch DevTools. Will probably be instantly acquainted to anybody with browser debugging expertise.

Chrome DevTools

The + Add folder to workspace hyperlink lets you choose the place the Node.js information are positioned in your system, so it turns into simpler to load different modules and make modifications.

Clicking any line quantity units a breakpoint, denoted by a inexperienced marker, which stops execution when that code is reached:

Chrome DevTools breakpoint

Variables may be added to the Watch pane on the appropriate by clicking the + icon and getting into their title. Their worth is proven each time execution is paused.

The Name Stack pane reveals which features have been referred to as to succeed in this level.

The Scope pane reveals the state of all out there native and world variables.

The Breakpoints pane reveals an inventory of all breakpoints and permits them to be enabled or disabled.

The icons above the Debugger paused message can be utilized to renew execution, step over, step into, step out, step via, deactivate all breakpoints, and pause on exceptions.

Node.js Debugging with VS Code

VS Code Node.js debugging may be launched with none configuration if you’re operating a Node.js software in your native system. Open the beginning file (sometimes index.js), activate the Run and Debug pane, and click on the Run and Debug Node.js (F5) button.

VS Code debugger

The debugging display screen is much like Chrome DevTools with a Variables, Watch, Name stack, Loaded scripts, and Breakpoints checklist.

VS Code breakpoint

A breakpoint may be set by clicking the gutter subsequent to the road quantity. You too can right-click.

VS Code breakpoint options

With this right-click, you possibly can set the next:

An ordinary breakpoint.

A conditional breakpoint which stops when standards are met — for instance, depend > three.

A logpoint, which is successfully console.log() with out code! Any string may be entered with expressions denoted in curly braces — for instance, depend to show the worth of the depend variable.

VS Code logpoint

Be aware: don’t overlook to hit Return for VS Code to create your conditional breakpoint or logpoint.

The debugging icon bar on the high can be utilized to renew execution, step over, step into, step out, restart, or cease the applying and debugging. An identical choices are additionally out there from the Debug merchandise within the menu.

For extra data, seek advice from Debugging in Visible Studio Code.

Superior Debugging Configuration

Additional configuration is required if you’re debugging a distant service or want to make use of completely different launch choices. VS Code shops launch configurations in a launch.json file generated contained in the .vscode folder inside your challenge. To generate or edit the file, click on the cog icon on the high proper of the Run and Debug pane.

VS Code launch configuration

Any variety of configuration settings may be added to the configurations array. Click on the Add Configuration button to decide on an possibility. VS Code can both:

launch a course of utilizing Node.js itself, or
connect to a Node.js inspector course of, maybe operating on a distant machine or Docker container

Within the instance above, a single Nodemon launch configuration has been outlined. Save launch.json, choose nodemon from the drop-down checklist on the high of the Run and Debug pane, and click on the inexperienced begin icon.

VS Code launch

For additional data, see VS Code Launch configurations.

The Node.js Debugging Information offers recommendation for different IDEs and editors together with Visible Studio, JetBrains, WebStorm, Gitpod, and Eclipse. Atom additionally has a node-debug extension.

ndb provides an improved debugging expertise with highly effective options resembling attaching to baby processes and script blackboxing so solely code in particular folders is proven.

The IBM report-toolkit for Node.js works by analyzing information output when node is run with the –experimental-report possibility.

Lastly, industrial companies resembling LogRocket and Sentry.io combine together with your dwell net software in each the shopper and the server to file errors as they’re encountered by customers.

Get Debugging!

Node.js has a variety of nice debugging instruments and code analyzers which may enhance the pace and reliability of your software. Whether or not or not they will tempt you away from console.log() is one other matter!

Craig is a contract UK net marketing consultant who constructed his first web page for IE2.zero in 1995. Since that point he is been advocating requirements, accessibility, and best-practice HTML5 methods. He is created enterprise specs, web sites and on-line purposes for corporations and organisations together with the UK Parliament, the European Parliament, the Division of Vitality & Local weather Change, Microsoft, and extra. He is written greater than 1,000 articles for SitePoint and you’ll find him @craigbuckler.

Leave a Reply