20

For example sake, I'm running the most basic webServer in node (I'm using windows) with the following code (named server.js):

    var http = require('http');
       http.createServer(function (req, res) {
         res.writeHead(200, {'Content-Type': 'text/plain'});
         res.end('Hello World\n');
       }).listen(1337, '127.0.0.1');
    console.log('Server running at http://127.0.0.1:1337/');

I would like to run this as a child process, and am successfully doing so with the following:

var exec = require('child_process').exec;
var serv = exec('node server.js', function(error, stdout, stderr){
    console.log('outputs & errors:' + error, stdout, stderr);
});

However, I receive nothing once I run the second file. No "outputs & errors", no "Server running at...". If I type localhost:1337 in a browser, I get "hello world" though, so I know it's running. Is there a way to pipe that "server running..." so I can be "sure" it's listening?

mayorbyrne
  • 495
  • 1
  • 5
  • 16

3 Answers3

29

Exec will return STDOUT and STDERR when the child finishes, see exec. That's why you do not see any output, when the server starts.

What you want is fork, which automatically connects the child process STDOUT and STDERR to your parent's. This is the preferred way if your child process is a node process.

If you want to use exec you can use the child processe's streams to get your data, e.g.:

child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
topek
  • 18,609
  • 3
  • 35
  • 43
  • 1
    Fantastic. I had looked at spawn, but neglected to look at Fork, which appears to be exactly what I need. – mayorbyrne Mar 06 '13 at 21:30
  • Is it possible to get the coloring working when streaming the child stdout? For example I'm executing another gulp command which normally has a nice colored output but when the two pipes are connected the output from the child gulp appears all as white chars loosing the coloring. – Corneliu Nov 20 '15 at 23:49
  • 1
    I found the answer: http://stackoverflow.com/questions/7725809/preserve-color-when-executing-child-process-spawn – Corneliu Nov 20 '15 at 23:52
2
var child_process = nw.require('child_process');
var spawn = child_process

//The following is on windows and I record stdout and stderr to my logger

var proc = spawn('cmd.exe', ['/S', '/C', script_path]);
proc.stdout.on('data', function(data) {
       logger(logtag, 'proc_stdout: ' + data);
});

proc.stderr.on('data', function(data) {
    logger(logtag, 'proc_stderr: ' + data);
});
Verdigrass
  • 1,203
  • 12
  • 14
1

Just specify that you want the child process to inherit stdio of parent one:

require('child_process').exec('node server.js', { stdio: 'inherit' });
Qwertiy
  • 19,681
  • 15
  • 61
  • 128