Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug Node.JS child forked process?

I'm trying to debug the child Node.JS process created using:

var child = require('child_process'); child .fork(__dirname + '/task.js'); 

The problem is that when running in IntelliJ/WebStorm both parent and child process start on the same port.

debugger listening on port 40893 debugger listening on port 40893 

So it only debugs the parent process.

Is there any way to set IntelliJ to debug the child process or force it to start on a different port so I can connect it in Remote debug?

like image 466
Guy Korland Avatar asked May 30 '13 15:05

Guy Korland


People also ask

How does NodeJS handle child process?

Usually, Node. js allows single-threaded, non-blocking performance but running a single thread in a CPU cannot handle increasing workload hence the child_process module can be used to spawn child processes. The child processes communicate with each other using a built-in messaging system.

How do you debug Gatsby nodes?

Press Ctrl + , or ⌘ + , to open your preferences. Type node debug into the search bar. Make sure the Auto Attach option is set to on . Set breakpoints and debug!

Can we create child process in node?

Node. js also provides a way to create a child process that executes other Node. js programs. Let's use the fork() function to create a child process for a Node.


2 Answers

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

like image 59
davidforneron Avatar answered Oct 05 '22 15:10

davidforneron


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); } 
like image 26
Miroslav Bajtoš Avatar answered Oct 05 '22 15:10

Miroslav Bajtoš