nodejs wait for exec in function

Solution 1:

Since the command is executed asynchronously you will want to use a callback to handle the return value once the command has finished executing:

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

Solution 2:

you can use promise as :

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