child_process
模块使我们在一个运行良好的子进程内运行一些能够进入操作系统的命令
spawn
创建一个子进程
语法:spawn(command, [args], [options])
const {spawn} = require('child_process')
const fs = require('fs')
for (var i = 0; i < 3; i++) {
var workerProcess = spawn('node', ['support.js', i])
workerProcess.stdout.on('data', function (data) {
console.log('stdout: ' + data)
})
workerProcess.stderr.on('data', function (data) {
console.log('stderr: ' + data)
})
workerProcess.on('close', function (code) {
console.log('child process exited with code ' + code)
})
}
exec
使用子进程执行命令,不缓存子进程的输出,并将子进程的输出以回调函数参数的形式返回
语法:exec(command, [options], callback)
console.log('进程 ' + process.argv[2] + ' 执行。')
const fs = require('fs')
const child_process = require('child_process')
for (var i = 0; i < 3; i++) {
var workerProcess = child_process.exec(
'node support.js ' + i,
function (error, stdout, stderr) {
if (error) {
console.log(error.stack)
console.log('Error code: ' + error.code)
console.log('Signal received: ' + error.signal)
}
console.log('stdout: ' + stdout)
console.log('stderr: ' + stderr)
}
)
workerProcess.on('exit', function (code) {
console.log('子进程已退出,退出码 ' + code)
})
}
fork
创建一个子进程,并在父进程中继续执行
语法:fork(modulePath, [args], [options])
console.log('进程 ' + process.argv[2] + ' 执行。')
const fs = require('fs')
const child_process = require('child_process')
for (var i = 0; i < 3; i++) {
var worker_process = child_process.fork('support.js', [i])
worker_process.on('close', function (code) {
console.log('子进程已退出,退出码 ' + code)
})
}