nodejs在函数中等待exec

RGe*_*RGe 3 javascript function exec node.js

我喜欢在自定义函数中集成来自nodejs的exec来处理这一函数中的所有错误.

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

function os_func() {
    this.execCommand = function(cmd) {
        var ret;
        exec(cmd, (error, stdout, stderr) => {
            if (error) {
                console.error(`exec error: ${error}`);
                return;
            }
            ret = stdout;
        });
        return ret;
    }
}
var os = new os_func();
Run Code Online (Sandbox Code Playgroud)

此函数返回undefined,因为当值返回时exec未完成.我怎么解决这个问题?我可以强制该函数等待exec吗?

8ct*_*pus 21

另一种使用 ES6 模块的解决方案:

import fs from "node:fs";
import {exec} from "node:child_process";
import util from "node:util";

// promisify exec
const execPromise = util.promisify(exec);

try {
  // wait for exec to complete
  const {stdout, stderr} = await execPromise("ls -l");
} catch (error) {
  console.log(error);
}
Run Code Online (Sandbox Code Playgroud)


Hyd*_*dan 8

由于命令是异步执行的,因此一旦命令执行完毕,您将需要使用回调来处理返回值:

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

function os_func() {
    this.execCommand = function(cmd, callback) {
        exec(cmd, (error, stdout, stderr) => {
            if (error) {
                console.error(`exec error: ${error}`);
                return;
            }

            callback(stdout);
        });
    }
}
var os = new os_func();

os.execCommand('SomeCommand', function (returnvalue) {
    // Here you can get the return value
});
Run Code Online (Sandbox Code Playgroud)


Sou*_*pta 8

您可以将承诺用作:

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

function os_func() {
    this.execCommand = function (cmd) {
        return new Promise((resolve, reject)=> {
           exec(cmd, (error, stdout, stderr) => {
             if (error) {
                reject(error);
                return;
            }
            resolve(stdout)
           });
       })
   }
}
var os = new os_func();

os.execCommand('pwd').then(res=> {
    console.log("os >>>", res);
}).catch(err=> {
    console.log("os >>>", err);
})
Run Code Online (Sandbox Code Playgroud)


yok*_*zor 6

exec将以异步方式处理它,因此您应该收到回调或返回承诺。

为了使其同步,您可以做的一件事是使用execSync代替:

https://nodejs.org/api/child_process.html#child_process_child_process_execsync_command_options

child_process.execSync() 方法通常与 child_process.exec() 相同,但该方法在子进程完全关闭之前不会返回。当遇到超时并发送killSignal时,该方法将不会返回,直到进程完全退出。注意,如果子进程拦截并处理了SIGTERM信号并且不退出,则父进程将等待,直到子进程退出。


Nei*_*eil 5

添加对我有用的内容,因为以上都没有达到目的!

const { exec } = require("child_process");
const util  = require("util");
const execPromise = util.promisify(exec);

function parentFunction() {
...
  // Trigger 'exec', then a-wait for it to finish
  await execWrapper('<your-command-here>');
...
}

...
async function execWrapper(cmd) {
  const { stdout, stderr } = await execPromise(cmd);
  if (stdout) {
    console.log(`stderr: ${stdout}`);
  }
  if (stderr) {
    console.log(`stderr: ${stderr}`);
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:这不是您的示例,而只是一个通用示例;对我来说 - 这cmd是一个 Dockerbuild命令。如果需要,您可能可以execWrapper归还stdout