Start another node application using node.js?
Asked Answered
P

2

44

I have two separate node applications. I'd like one of them to be able to start the other one at some point in the code. How would I go about doing this?

Personage answered 18/9, 2013 at 0:57 Comment(0)
B
53

Use child_process.fork(). It is similar to spawn(), but is used to create entire new instances of V8. Therefore it is specially used for running new instances of Node. If you are just executing a command, then use spawn() or exec().

var fork = require('child_process').fork;
var child = fork('./script');

Note that when using fork(), by default, the stdio streams are associated with the parent. This means all output and errors will be shown in the parent process. If you don't want the streams shared with the parent, you can define the stdio property in the options:

var child = fork('./script', [], {
  stdio: 'pipe'
});

Then you can handle the process separately from the master process' streams.

child.stdin.on('data', function(data) {
  // output from the child process
});

Also do note that the process does not exit automatically. You must call process.exit() from within the spawned Node process for it to exit.

Blow answered 18/9, 2013 at 1:1 Comment(5)
Thanks! Is there any way for me to pass arguments to the child process - say, sending it a variable from the parent application?Personage
Arguments are passed as an array as the second argument. So it'd be like this: fork('./script, ['arg1','arg2']); If you mean passing variables after the child has been spawned, use child.send() and listen in the child with process.on('message', function(message) {});.Blow
Hello, do you know if there is a way to test if a nodejs child process is running? - Thanks!Romain
@Blow How can we get details from mongodb in child page and send to main page to print on console. Please look at #43490711Changeover
I realise this answer is from long ago, but is that part about "note that the process does not exit automatically. You must call process.exit() from within the spawned Node process for it to exit." still relevant? I searched on the docs site, and cannot find any mention of this. nodejs.org/api/child_process.htmlShah
E
3

You can use the child_process module, it will allow to execute external processes.

var childProcess = require('child_process'),
     ls;

 ls = childProcess.exec('ls -l', function (error, stdout, stderr) {    if (error) {
     console.log(error.stack);
     console.log('Error code: '+error.code);
     console.log('Signal received: '+error.signal);    }    console.log('Child Process STDOUT: '+stdout);    console.log('Child Process STDERR: '+stderr);  });

 ls.on('exit', function (code) {    console.log('Child process exited with exit code '+code);  });

http://docs.nodejitsu.com/articles/child-processes/how-to-spawn-a-child-process

Envelope answered 18/9, 2013 at 1:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.