execa执行命令工具

676 阅读1分钟

介绍

Execa 是一个 Node.js 库,可以替代 Node.js 的原生 child_process 模块,用于执行外部命令。Execa拥有更好的性能、可靠性和易用性,支持流式传输、输出控制、交互式 shell 等功能,并跨平台兼容 Windows、macOS 和 Linux 等操作系统。同时,Execa 还支持 Promise API,提供更好的异步控制和异常处理机制。使用 Execa 可以简化发现和解决常见的子进程处理问题,是 Node.js 开发中非常有用的工具之一。 官网地址:github.com/sindresorhu…

使用

安装

yarn add execa -D

简单使用

import { execa } from 'execa';

await execa('npm',// 执行命令
    ['run', 'dev'],// 执行参数
    { stdio: 'inherit' }// 配置。stdio: 'inherit'表示继承主进程的输入输出流、忽略输入输出流
);

api介绍

API解释
execa(file, arguments, options?)相当于child_process.execFile() 和child_process.spawn()
execa.sync(file, arguments?, options?)同步执行文件
execa.command(command, options?)与execa()相同,上文中execa('echo', ['unicorns'])与execa.command('echo unicorns')相同
execa.commandSync(command, options?)与execa.sync()相同
execa.node(scriptPath, arguments?, options?)执行Node脚本

参数说明

参数说明如下:

  • file:将要运行的命令;
  • arguments:参数数组;
  • options:选项对象,如用shell,可以设置为{shell:true}。
  • command:命令+参数的集合;
  • scriptPath: 运行模块路径;