Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
119 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...