1

I have the following function:

function exec(command) {
    const stdout = {
        command: null,
        output: null
    };
    stdout.command = command;
    chproc.exec(command, (error, out, stderr) => {
        if (error || stderr) {
            console.error(error || stderr);
            return;
        }
        temp = out;
    });
    stdout.output = temp;
    return stdout;

where const chproc = require('child_process'); , I've been trying to store the output in the callback function in chproc.exec in the object stdout, but it does so only within the scope of the callback function not the outer exec function which goes back to null. The thing is, this works, if stdout is in global scope and I am writing each code line in the Node.js terminal -if I run the file, this too doesn't work for some reason-, so as you see, I am in a confusing mess, if anyone can help clear it up, much appreciated.

AGawish
  • 98
  • 1
  • 6

1 Answers1

-1

chproc.exec accepts command and a callback , which gets called when exec completes its call. So if you are wrapping it in your own function , then I suggest you keep the same function signature.

function exec(command, callback) {
    const stdout = {
        command: null,
        output: null
    };
    stdout.command = command;
    let temp;
    chproc.exec(command, (error, out, stderr) => {
        if (error || stderr) {
            console.error(error || stderr);
            return;
        }
        callback(out);
    });
    return stdout;
}

exec('ls', function (output) {
    console.log(output);
});
Omkarpb
  • 9
  • 2