Search code examples
javascriptnode.jschild-process

I have a execution flow problem whith nodejs child process


I am wanting to make a function that receives a String that is the input and returns me an output as a string, but I am not able because of the response delay

var resultado = "old value";

function execShell(cmd) {

exec("uname", (error, data, getter) => {
  if(error){
    console.log("error",error.message);
    return;
  }
  if(getter){
    console.log("data",data);
    return;
  }
  console.log(`need before exec: ${data}`);
  resultado = data;

});
}

/* shell command for Linux */

execShell('uname');

console.log(`need after exec: ${resultado}`);

Solution

  • What happens here is, that that the callbacks are not executed from top to bottom. This means that console.log(need after exec: ${resultado}); is called directly after execShell and the child process hasn't returned yet.

    You could use the sync version to execute it:

    const cp = require("child_process");
    const result = cp.execSync("uname").toString(); // the .toString() is here to convert from the buffer to a string
    console.log(`result after exec ${result}`);
    

    The docs are https://nodejs.org/dist/latest-v14.x/docs/api/child_process.html#child_process_child_process_execsync_command_options

    You could use a NPM package that helps with the shell handling if that's what you are building: https://github.com/shelljs/shelljs which wraps alot of the child process parts with an easier API.