nodejs在函数中等待exec

我喜欢将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值在返回时还没有完成。 我该如何解决? 我可以强制该function等待执行吗?

由于该命令是asynchronous执行的,因此一旦命令执行完毕,您将希望使用callback来处理返回值:

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

exec将以asynchronous的方式处理它,所以你应该收到一个callback或返回一个承诺。

你可以做的一件事是使用execSync代替:

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

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

你可以使用promise作为:

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

你可以用callback来完成。 也许你可以尝试这样的事情:

 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... }