Home > Software design >  Extracting stdout return value in node js
Extracting stdout return value in node js

Time:09-27

I got a bash script, which output a integer value and how do I grab that value as a variable.

var exec = require('child_process').exec;
var ftpsize;
exec('~/docker-project/ftp.check.sh',
  function (error, stdout, stderr) {
    if (error !== null) {
      console.log(error);
    } else {
    ftpsize=stdout;
    console.log('stdout: '   stdout);
    console.log('stderr: '   stderr);
    }
});

console.log('stdout: '   ftpsize);

stdout: 889951 and ftpsize as undifined, how do I extract the stdout as variable.

CodePudding user response:

Because the callback that run after ftp.check.sh execute is called asynchronously, ftpsize will be undefined because the order of execution is:

  1. start exec
  2. console.log('stdout: ' ftpsize); -> undefined
  3. exec complete, ftpsize=stdout;

What you may want to look at is the concept of a "promise" in javascript. But, long story short, you want to define a function that return a "future value", and then you want to "await" for it to complete.

async function run() {
  return new Promise((resolve, reject) => {
    exec('~/docker-project/ftp.check.sh', function (error, stdout, stderr) {
      if (error !== null) {
        console.log(error);
        reject(error)
        return
      }

      console.log('stdout: '   stdout);
      console.log('stderr: '   stderr);
      resolve(stdout)
    })
  })
}

which you can then consume with const ftpsize = await run() or run().then(ftpsize => { /* ... */ })

  • Related