How to programmatically detect debug mode in nodejs?

Viewed 24751

I've seen this question asked of other platform/languages - any ideas? I'd like to do something like:

if (detectDebug())
{
    require('tty').setRawMode(true);    
    var stdin = process.openStdin();

    stdin.on('keypress', function (chunk, key) {
        DoWork();
    }
}
else
{
    DoWork();
}

I'd like to be able to toggle keyboard input as a start for the script when debugging so that I can have a moment to fire up chrome to listen to my node-inspector port.

***Quick update - I'm guessing I can actually use "process.argv" to detect if --debug was passed in. Is this the best/right way?

12 Answers

There is a node.js native support that using inspector.url() to check if there is active inspector, it just shows if process is debug mode or not currently. See doc for more.

The global v8debug variable mentioned in the other answers seem to be removed in Node v7.0.0 (see https://github.com/nodejs/node/issues/9617). Also, checking process arguments (i.e. process.execArgv) seem to be unreliable since Node can enter debug mode at runtime. VS Code, for example, doesn't always starts Node with the --inspect option even when debugging. (depend on your debug config)

The most reliable solution I could find is to use inspector.url() to check if Node is listening for debug connections.

const inspector = require('inspector');

function isInDebugMode() {
    return inspector.url() !== undefined;
}

I have tested this method with Node versions v12.22.1, v14.16.1, and v16.1.0 and it worked for all of them.

I had the same issue, how to check the app to see if it is running on --inspect.

I m on nodejs 14, and the solution with the v8debug that mentioned above, looks that it does not work any more, for clarity i post the message that i get when i try --debug.

node: [DEP0062]: node --debugandnode --debug-brkare invalid. Please usenode --inspectandnode --inspect-brk instead.

Solution

So how i tackle with this, is to query the process.execArgv which is exactly what you need too.

snipet:
const isInspect = process.execArgv.join() === '--inspect' //or ....process.execArgv.toString() === ...

This execArgv, as the docs state:
The process.execArgv property returns the set of Node.js-specific command-line options passed when the Node.js process was launched. These options do not appear in the array returned by the process.argv property, and do not include the Node.js executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent.
More in the docs: https://nodejs.org/docs/latest-v6.x/api/process.html#process_process_execargv

Related