Here is the code I'm using:
const { exec } = require("child_process");
exec("ls -la", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
It returns "0" and then logs in the console the correct result.
But how to directly return the result instead of console.log?
Some answers have pointed out how to convert it into a Promise.
You can't return a value from that callback, because it would not be passed to anything. What you can do is defining a Promise that passes the stdout to the resolve method. Here's an example:
What I am doing here is defining a function that creates a new Promise. The Promise will execute your code (the ls -la call), and will fire an exception if there is an error, rejecting the Promise, or it will solve the Promise if everything is fine, passing the stdout value.
You can then use this Promise with something like this:
the out variable will contain your stdout.
If you want some function that returns that value, it should be awaited from this function. An example could be this:
Note that you can only call unwrapLs() from inside an async function, because you have to await for its value. In fact, this would be equivalent to calling ls() by awaiting it, but you can only do it from inside an async function.