如何使用 node 的 child_process.exec() 和 promises

How to use node's child_process.exec() with promises

我尝试使用 node.js(docker exec 命令)顺序执行长进程。

我愿意:

const childProcess = require('child_process');

const execWithPromise = async command => {
    return new Promise(async resolve => {
        const process = childProcess.exec(command);

        process.on('exit', err => resolve(err));
        process.on('close', err => resolve(err));
    });
};

const run = async () => {
    await execWithPromise('/usr/local/bin/docker exec -i -t cucumber node long-running-script.js');
    await execWithPromise('/usr/local/bin/docker exec -i -t cucumber node long-running-script.js');
};

run();

但是承诺立即得到解决,结果为 1。在这两种情况下。该命令在命令行上运行得很好。

为什么立即返回?

child_process.exec 期望回调作为第二个或第三个参数。这不是 return 承诺。根据您的用例和节点版本,您有几个选择。

使用回调和 return 解析。

return new Promise(async resolve => {
     childProcess.exec(command, (err, stout, sterr) {
        resolve(err ? stout : sterr)
      }
  });

改为使用 spawn(保留大部分代码)

const execWithPromise = async command => {
    return new Promise(async (resolve, reject) => {
        const process = childProcess.spawn(command);
        process.on('data', data => resolve(data));
        process.on('error', err => reject(err));
        process.on('close', err => reject(err));
    });
};

将 execSync 与 try catch 结合使用

return new Promise(async (resolve, reject) => {
    try {
        resolve(childProcess.execSync(command));
    } catch(error) {
      reject(error) 
    }
});

我知道这是一个老问题,但这是我不久前在节点中发现的一个有用的工具...所以,假设您有一个节点文件 app.ts,在打字稿中是...

app.ts

import utils from 'util'; // The thing that is useful, it has a bunch of useful functions
import { exec } from 'child_process'; // The exec import

export function execute(command: string): Promise<any> {
    // Not too concerned about the return type here
    return utils.promisify(exec)(command);
}

const run = async () => {
    await execute('/usr/local/bin/docker exec -i -t cucumber node long-running-script.js');
    await execute('/usr/local/bin/docker exec -i -t cucumber node long-running-script.js');
};

run();

在 js 中可能是这样的

app.js

const utils = require('util');
const exec = require('child_process').exec;

function execute(command) {
    return utils.promisify(exec)(command);
}

const run = async () => {
    await execute('/usr/local/bin/docker exec -i -t cucumber node long-running-script.js');
    await execute('/usr/local/bin/docker exec -i -t cucumber node long-running-script.js');
};

run();