简体   繁体   中英

How to set variable from child_process.exec()

I have a simple function to run a system app from the web.

server.route({
  method: 'POST',
  path: '/executeMain',
  handler: (req, res) => {
    var success = false;
    exec("./main", (error, stdout, stderr) => {
      if (error) {
        console.log('error: ' + error.message);
        return;
      }
      if (stderr) {
        console.log('error: ' + stderr);
        return;
      }
      console.log(stdout);
      success = true;
    });

    if (success) {
      return res.response("OK").code(200);
    }
    else {
      return res.response("ERR").code(500);
    }
  }
});

In exec function, I want to set success to true, but it never happens. Can anybody help me and explain to me why this is don't work.

child_process.exec() is an asynchronous function. So the process starts running the background and the function returns immediately. So you are checking the value of success before the process finishes and before it's been set.

Your handler will need to also be asynchronous since it relies on the return value of an asynchronous function. Something like:

server.route({
  method: 'POST',
  path: '/executeMain',
  handler: (req, res) => {
    return new Promise( (resolve, reject) => {
        exec("./main", (error, stdout, stderr) => {
            if (error) {
                console.log('eror: ' + error.message);
                reject( res.response("ERR").code(500) )
            }
            if (stderr) {
                console.log('error: ' + stderr);
                reject( res.response("ERR").code(500) )
            }

            console.log(stdout);
            resolve( res.response("OK").code(200) )
        });
    });
}

On another note, you probably don't want to throw an error just because stderr is true. Many programs write to stderr even when successful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM