nodejs的child_process
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:配置
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)