execa
人类的进程执行。
为什么
该软件包通过以下方式改进了 child_process 方法:
- Promise 接口。
 - 从输出中删除最后的换行符,这样您就不必执行 stdout.trim() 。
 - 支持跨平台的 shebang 二进制文件。
 - 改进的 Windows 支持。
 - 更高的最大缓冲区。 100 MB,而不是 200 KB。
 - 按名称执行本地安装的二进制文件。
 - 在父进程终止时清除派生的进程。
 - 从 stdout 和 stderr 获取交错输出,类似于在终端上打印的输出。 (仅异步)
 - 可以将文件和参数指定为没有 shell 的单一字符串
 - 更多描述性错误。
 
安装
$ npm install execa
用法
const execa = require('execa');
(async () => {
    const {stdout} = await execa('echo', ['unicorns']);
    console.log(stdout);
    //=> 'unicorns'
})();
通过管道将子进程 stdout 传输到父进程
const execa = require('execa');
execa('echo', ['unicorns']).stdout.pipe(process.stdout);
错误处理
const execa = require('execa');
(async () => {
    // Catching an error
    try {
        await execa('unknown', ['command']);
    } catch (error) {
        console.log(error);
        /*
        {
            message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
            errno: -2,
            code: 'ENOENT',
            syscall: 'spawn unknown',
            path: 'unknown',
            spawnargs: ['command'],
            originalMessage: 'spawn unknown ENOENT',
            shortMessage: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
            command: 'unknown command',
            stdout: '',
            stderr: '',
            all: '',
            failed: true,
            timedOut: false,
            isCanceled: false,
            killed: false
        }
        */
    }
})();
取消派生的进程
const execa = require('execa');
(async () => {
    const subprocess = execa('node');
    setTimeout(() => {
        subprocess.cancel();
    }, 1000);
    try {
        await subprocess;
    } catch (error) {
        console.log(subprocess.killed); // true
        console.log(error.isCanceled); // true
    }
})()
用同步方法捕获错误
try {
    execa.sync('unknown', ['command']);
} catch (error) {
    console.log(error);
    /*
    {
        message: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',
        errno: -2,
        code: 'ENOENT',
        syscall: 'spawnSync unknown',
        path: 'unknown',
        spawnargs: ['command'],
        originalMessage: 'spawnSync unknown ENOENT',
        shortMessage: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',
        command: 'unknown command',
        stdout: '',
        stderr: '',
        all: '',
        failed: true,
        timedOut: false,
        isCanceled: false,
        killed: false
    }
    */
}
杀死进程
使用 SIGTERM,并在 2 秒钟后用 SIGKILL 杀死它。
const subprocess = execa('node');
setTimeout(() => {
    subprocess.kill('SIGTERM', {
        forceKillAfterTimeout: 2000
    });
}, 1000);
API
请参考自述文件。
(The second edition revised by vz on 2020.08.02)