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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…