javascriptnode.jsshelljs

Returning a value trough ShellJS


For my project I need a specific value from a token that I get trough executing a shell file trough shell JS. The token is in the output of the shellJS.

My problem is that I cannot return my the value in the function to use the token elsewhere.

Here is my code :

const shell = require('shelljs');


const bypass = () => {
    let R2;

    var put = shell.exec('sh ./scripts/script.sh', (err, stdout) => {

        if (err) {
            console.log(err)
        } else {
            let tableau = (stdout.split(' '));
            let test = tableau[tableau.length - 1].split(':');
            let test3 = (test[1]).split(',');
            R2 = (test3[0].substr(1, test3[0].length - 2));
        }
    })
    return R2

}

bypass();

I would like to be able to GET the R2 value when I execute the function such as shown.

Any ideas would be appreciated !

Thanks.

Best regards,

Aymeric.


Solution

  • The shell.exec, when executed synchronously (default), returns a ShellString.

    ShellString has .stdout, .stderr and .code.

    var put = shell.exec('sh ./scripts/script.sh');
    
    if (put.stderr === ''){
    
      let tableau = (put.stdout.split(' '));
      let test = tableau[tableau.length - 1].split(':');
      let test3 = (test[1]).split(',');
      let R2 = (test3[0].substr(1, test3[0].length - 2));
    
    }