child_process 模塊提供了衍生子進程的能力
異步方式:spawn、exec、execFile、fork
同步方式:spawnSync、execSync、execFileSync
說明:
.exec()、.execFile()、.fork() 底層都是通過 .spawn() 實現的
.exec()、execFile() 還提供了回調,當子進程停止的時候執行
.spawnSync()是 .spawn()的同步版 ,將會阻塞 Node.js 事件循環
.execSync() 是 .exec() 的同步版本,將會阻塞 Node.js 事件循環
.execFileSync() 是 .execFile() 的同步版本,將會阻塞 Node.js 事件循環
(1) spawn
使用指定的命令行參數創建新進程
child_process.spawn(command[, args][, options])
command: 要執行的指令
args: Array字符串參數數組
options: 配置項
(2) exec
創建子shell,可以直接執行shell管道命令,有回調
只適用於命令執行結果數據小的情況
child_process.exec(command[, options][, callback])
command: 要執行的指令
options: 配置項
callback:回調
"use strict"; var path = require("path"), execFile = require("child_process").exec, fs = require('fs'); module.exports = function convert(source, dest, options) { return new Promise(function(resolve, reject) { var convertPath; if (options && options.path) { convertPath = options.path + '/Convert'; } else { convertPath = 'Convert'; } if (!fs.existsSync(source)) { reject('Unable to open the source file.'); return; } var args = [source, dest]; if (options && options.args) { args = args.concat(options.args); } var cmd = convertPath+" "+args.join(" "); execFile(cmd, function(err, stdout, stderr) { if (err) { reject(err); } else if (stderr.lenght > 0) { reject(new Error(stderr.toString())); } else { resolve(); } }); }); };
(3)execFile
用於執行文件,不會創建子shell環境
child_process.execFile(file[, args][, options][, callback])
file:要運行的可執行文件的名稱或路徑
args:字符串參數的列表
options:配置項
callback:回調
exec() 、execFile() 區別:
是否創建了shell
"use strict"; var path = require("path"), execFile = require("child_process").execFile, fs = require('fs'); module.exports = function convert(source, dest, options) { return new Promise(function(resolve, reject) { var convertPath; if (options && options.path) { convertPath = options.path + '/Convert'; } else { convertPath = 'Convert'; } if (!fs.existsSync(source)) { reject('Unable to open the source file.'); return; } var args = [source, dest]; //If user supplies any args concat them to the args array if (options && options.args) { args = args.concat(options.args); } execFile(convertPath, args, { maxBuffer: 1024 * 2000 }, function(err, stdout, stderr) { if (err) { reject(err); } else if (stderr.lenght > 0) { reject(new Error(stderr.toString())); } else { resolve(); } }); }); };
(4)fork
spawn方法的一個特例,fork用於執行js文件創建Node.js子進程
fork方式創建的子進程與父進程之間建立了IPC通信管道
常用於父子進程的通信
child_process.fork(modulePath[, args][, options])
modulePath:要在子進程中運行的模塊
args:參數
options:配置