'Javascript exec() - a generic function that exec's and returns stdout, stderr
I'm super new to JS and am struggling with a very basic task as I familiarize myself with it. I want to create a simple run(cmd) function that would receive a string with a command, and return an object containing stderr and stdout.
From what I found, I need to use exec or spawn, but I'm having trouble turning the examples online into a returning function:
const { exec } = require("child_process");
let run(cmd) = exec(cmd, (error, stdout, stderr) => {
ret = {
out: "",
err: "",
msg: ""
}
if (error) {
ret.msg = error.message;
}
if (stderr) {
ret.err = stderr;
}
ret.out = stdout;
return ret;
});
out = run("ls -al");
console.log(out);
This doesn't work and I'm probably making mistakes on multiple levels here
UPDATE: The snippet I posted doesn't work, no outputs, just errors. I posted it because it is very simple and straightforward in terms of showing what I want to achieve. If I need to drop exec() for something else - I'm happy to hear suggestions.
Solution 1:[1]
exec() is a callback-based function and there is no way to do what you are doing without promisifying exec() or using a callback. You are returning from a function of it's own.
This is not even correct syntax for a function. You probably want to do something like this:
let run = (cmd, callback) => {
exec(cmd, (e, so, se) => {
// do stuff with the e, so, and se
callback(e, so, se);
});
};
run('ls', (e, so, se) => {
// at this point you might just as well use exec()
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | 0xLogN |