每天一个nodejs模块-child_process

410 阅读2分钟

这是我参与更文挑战的第4天,活动详情查看: 更文挑战

前言

在很早之前,我刚接触到shell命令时,曾经思考过,如果一个shell脚本可以让我通过接口来触发的话,是不是就会很大程度的解放我们的无用操作(部署过程),后来才知道,github有提供的webhook这种形式的api,让我们可以监听到一个仓库的变更通知,今天我们不说webhook,主要说一下nodejs的child_process模块,它可以用来创建子进程,可以直接在nodejs程序中调用shell命令去完成一些操作,接下来我们先来讲一下他大概会做那些操作吧:

exec

函数签名: child_process.exec(command, callback) exec接收两个参数,第一个参数是字符串,表示你要执行的命令行操作,第二个是错误优先回调,其中包括err对象,命令行的输出内容,具体使用如下:

const {exec } = require('child_process');
exec('ls', (err, stdout, stderr) => {
    console.log('err', err); // err null
    console.log('stdout', stdout); // stdout xxxx
    console.log('stderr', stderr); // stderr   
})

execFile

函数签名: child_process.execFile(file, options, callback), execFile和exec不同的地方在于,第一个参数是可执行文件,可以是系统环境变量,第二个参数是传递的参数,第三个参数是错误优先回调,具体使用如下

const {execFile} = require('child_process');
execFile('node', ['./20210611/exec.js'], (err, stdout, stderr) => {
    console.log('err', err); // err null
    console.log('stdout', stdout); // stdout err null stdout xxx stderr
    console.log('stderr', stderr); // stderr   
})

从上图的输出我们可以明显看出来,execFile在输出时,err输出为null, stdout输出为exec文件的输出内容,stderr输出为空,但是这样做有一点不好的在于,我们执行脚本操作时,其实是希望可以将内容实时输出到控制台的,而不是在执行完毕之后,在控制台一次性输出,那我们就用到了剩下的方法

spawn

函数签名: child_process.spawn(command, args, options),spawn接收三个参数,第一个参数为要执行的命令,第二个参数为数组,传入加入的参数,第三个参数为配置项,重要的是,spawn拥有自己的流信息,我们可以通过建立主进程和子进程之间的关系,进行信息的实时输出,具体如下

const {spawn} = require('child_process');
const child = spawn('ps', ['-ef'])
child.stdout.pipe(process.stdout); // 输出很多
child.stderr.pipe(process.stderr);

结语

以上就是今天的全部内容了,child_process当然不止这些内容,他的可玩性还远远没有被发掘,接下来的几天,我会主要输出命令行工具的几个主要模块,在进行这些模块的输出之后,大家可能会对命令行工具有一个清晰的认知。GitHub代码地址