How to programmatically detect debug mode in nodejs?
Solution 1:
NodeJS creates a v8debug
global object when running in debug mode: node debug script.js
So, a possible solution would be:
var debug = typeof v8debug === 'object';
For my use case, I use it because I want to avoid passing environment variables. My main node process starts child node processes and I want a node debug mainScript.js
to trigger debug mode for children as well (again, without passing env variables to child processes)
Solution 2:
I use this
var debug = typeof v8debug === 'object'
|| /--debug|--inspect/.test(process.execArgv.join(' '));
which supports, --debug
, --debug-brk
, --inspect
and --inspect=1234
Solution 3:
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.
Solution 4:
I think there's a bunch of confusion in this question.
Based on your question, I think what you really want is the node --debug-brk
command line flag. That will have node start v8 with a debugger running and automatically stop on a breakpoint before the first line of your .js
program. You don't need to reinvent this. I use this for debugging mocha tests, express.js startup issues, etc. This will eliminate your need to detect this manually.
Secondly, NODE_ENV=production
is nothing more than a convention that many programs use to indicate "you are running in production" and therefore certain things like really sending emails, using the real payment gateway, etc should be enabled. However what environment you are in when NODE_ENV
is NOT production (or is unset) should definitely NOT be assumed to be debugging. The most sane assumption there is that the environment is a development environment, but even then this whole convention is pretty brittle in my opinion.
Thirdly, just FYI check out tty.isatty() which will accurately tell you if your program is being run on an interactive terminal (like from a command shell). This will be false
when your program is being run by a process supervisor provided by your OS (upstart, sysvinit, etc). This check is commonly use to toggle command line programs between interactive and scripted modes. It's not entirely perfect or infallible, but it is widely adopted in the posix world.
Fourth, from some quick experimentation, the v8debug
global @Gabriel Petrovay indicates seems to only be set when doing node debug script.js
and not set when doing node --debug script.js
. Not sure why that is. If such a thing was reliable, that would seem like the most correct approach to finding out "is this v8 instance in debug mode".