簡體   English   中英

nodejs在函數中等待exec

[英]nodejs wait for exec in function

我喜歡將 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();

這個函數返回 undefined 因為當值返回時 exec 沒有完成。 我該如何解決? 我可以強制函數等待執行嗎?

由於命令是異步執行的,因此一旦命令完成執行,您將需要使用回調來處理返回值:

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
});

您可以將承諾用作:

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);
})

exec將以異步方式處理它,因此您應該收到回調或返回承諾。

為了使其同步,您可以做的一件事是改用execSync

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

child_process.execSync() 方法通常與 child_process.exec() 相同,不同之處在於該方法在子進程完全關閉之前不會返回。 當遇到超時並發送 killSignal 時,該方法在進程完全退出之前不會返回。 請注意,如果子進程攔截並處理了 SIGTERM 信號並且沒有退出,則父進程將等待子進程退出。

另一個使用 ES6 模塊的解決方案:

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

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

// wait for exec to complete
const {stdout, stderr} = await execPromise("ls -l");

你可以用回調來做到這一點。 也許你可以嘗試這樣的事情:

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

    });
}


function myCallback(ret){
      // TODO: your stuff with return value...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM