I tried the following code, it shows the res is undefined. How can I return the stdout?
function run_shell_command(command)
{
var res
exec(command, function(err,stdout,stderr){
if(err) {
console.log('shell error:'+stderr);
} else {
console.log('shell successful');
}
res = stdout
// console.log(stdout)
});
return res
}
child_process.exec() : spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete. child_process.execFile() : similar to child_process.exec() except that it spawns the command directly without first spawning a shell by default.
The exec() function in Node. js creates a new shell process and executes a command in that shell. The output of the command is kept in a buffer in memory, which you can accept via a callback function passed into exec() .
js allows single-threaded, non-blocking performance but running a single thread in a CPU cannot handle increasing workload hence the child_process module can be used to spawn child processes. The child processes communicate with each other using a built-in messaging system.
you can't get the return value except you use synchronous version of the exec
function. if you are still hellbent on doing that, you should use a callback
function run_shell_command(command,cb) {
exec(command, function(err,stdout,stderr){
if(err) {
cb(stderr);
} else {
cb(stdout);
}
});
}
run_shell_command("ls", function (result) {
// handle errors here
} );
or you can wrap the exec call in a promise and use async await
const util = require("util");
const { exec } = require("child_process");
const execProm = util.promisify(exec);
async function run_shell_command(command) {
let result;
try {
result = await execProm(command);
} catch(ex) {
result = ex;
}
if ( Error[Symbol.hasInstance](result) )
return ;
return result;
}
run_shell_command("ls").then( res => console.log(res) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With