How to debug Node.JS child forked process?

Solution 1:

Yes. You have to spawn your process in a new port. There is a workaround to debug with clusters, in the same way you can do:

Start your app with the --debug command and then:

var child = require('child_process');
var debug = typeof v8debug === 'object';
if (debug) {   
    //Set an unused port number.    
    process.execArgv.push('--debug=' + (40894));    
}    
child.fork(__dirname + '/task.js');

debugger listening on port 40894

Solution 2:

It is a known bug in node.js that has been recently fixed (although not backported to v0.10).

See this issue for more details: https://github.com/joyent/node/issues/5318

There is a workaround where you alter the command-line for each worker process, although the API was not meant to be used this way (the workaround might stop working in the future). Here is the source code from the github issue:

var cluster = require('cluster');
var http = require('http');

if (cluster.isMaster) {
  var debug = process.execArgv.indexOf('--debug') !== -1;
  cluster.setupMaster({
    execArgv: process.execArgv.filter(function(s) { return s !== '--debug' })
  });
  for (var i = 0; i < 2; ++i) {
    if (debug) cluster.settings.execArgv.push('--debug=' + (5859 + i));
    cluster.fork();
    if (debug) cluster.settings.execArgv.pop();
  }
}
else {
  var server = http.createServer(function(req, res) {
    res.end('OK');
  });
  server.listen(8000);
}

Solution 3:

Quick simple fix ( where using chrome://inspect/#devices )

var child = require('child_process');
child.fork(__dirname + '/task.js',[],{execArgv:['--inspect-brk']});

Then run your app without any --inspect-brk and the main process won't debug but the forked process will and no conflicts.

To stop a fork conflicting when debugging the main process ;

child.fork(__dirname + '/task.js',[],{execArgv:['--inspect=xxxx']});

where xxxx is some port not being used for debugging the main process. Though I haven't managed to easily connect to both at the same time in the debugger even though it reports as listening.

Solution 4:

I find that setting the 'execArgv' attribute in the fork func will work:

const child = fork('start.js', [], {
cwd: startPath,
silent: true,
execArgv: ['--inspect=10245'] });

Solution 5:

if "process.execArgv" doenst work you have to try:

if (debug) {
    process.argv.push('--debug=' + (40894));
}

this worked for me..