Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start another node application using node.js?

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?

like image 652
Hydrothermal Avatar asked Sep 18 '13 00:09

Hydrothermal


People also ask

How do I run a NodeJS script from within another NodeJS script?

To run a Node. js script from within another Node. js script with JavaScript, we can use the child_process module's fork function. require("child_process").

How do I run an external program from NodeJS?

To execute an external program from within Node. js, we can use the child_process module's exec method. const { exec } = require('child_process'); exec(command, (error, stdout, stderr) => { console. log(error, stdout, stderr) });


Video Answer


2 Answers

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.

like image 121
hexacyanide Avatar answered Sep 24 '22 06:09

hexacyanide


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

like image 35
JustEngland Avatar answered Sep 25 '22 06:09

JustEngland