nodejs的child_process
2024-08-30 12:27:55
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:配置
最新文章
- Linux中mongodb安装和导出为json
- Android AppWidget
- SK-Learn使用NMF(非负矩阵分解)和LDA(隐含狄利克雷分布)进行话题抽取
- 74 使用BitSet输出数组中的重复元素
- php数据库两个关联大表的大数组分页处理,防止内存溢出
- C# List 用法与示例
- PHP扩展开发(6) - VS2012下strncasecmp和fopen函数warning
- Java规范推荐
- 关于foo的一个面试题
- PAT 输出华氏-摄氏温度转换表
- python 字符串 字节
- 12.1、Libgdx的图像之持续性和非持续性渲染
- node.js 使用forever守护进程
- SSIS 调试和故障排除
- CentOS7查询最近修改的文件
- C# 防止content-type修改后上传恶意文件
- common lisp的几个基本概念
- Hbase 学习(九) 华为二级索引(原理)
- implicit和 explicit关键字
- bzxoj1090 字符串折叠