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:
const { exec } = require("child_process");
function ls() {
return new Promise((resolve, reject) => {
exec("ls -la", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
reject(error.message);
}
if (stderr) {
console.log(`stderr: ${stderr}`);
reject(stderr);
}
console.log(`stdout: ${stdout}`);
resolve(stdout);
});
});
}
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:
ls().then((out) => {
console.log(out);
})
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:
async function unwrapLs() {
const stdout = await ls();
return stdout;
}
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.