Read ChildProcess returned value from a shell command

31 Views Asked by At

I'm executing this ChildProcess function into a Nextjs API route but i cant read the value from it.

const output = exec(
    "curl -s -v https://test.com/index.php",
    (err, stdout, stderr) => {
      if (err) {
        console.error(err);
        process.exit(1);
      } else {
        var lines = stderr.split("\n");
        var numLines = lines.length;
        var i;
        let regex = /Set\-Cookie:\ SESSIDe08a=[0-9A-Za-z]*;\ /i;

        for (i = 0; i < numLines; i++) {
          var line = lines[i];
          if (regex.test(line)) {
            let n = line.replace(/^.*SESSIDe08a=([^;]+);[.]+$/, "$1");
            let l = n.replace(/^.*SESSIDe08a=/, "");
            let a = l.split(" ");
            let final = a[0].replace(";", "");

            return final; // <=== I need this value
          }
        }

      }
    }
  );

How do i read the returned final value?

1

There are 1 best solutions below

0
Arkin Solomon On

Since you have a callback function, when you return, you are returning the callback function, which is not passed upwards and returned from exec(). You will need to use a variable that is out of scope. However, the issue with this is that execution will continue. You will need to use a promise. Refer to this thread, and then:

let output;
try {
  const { stdout, stderr } = await exec("curl -s -v https://test.com/index.php");
  var lines = stderr.split("\n");
  var numLines = lines.length;
  var i;
  let regex = /Set\-Cookie:\ SESSIDe08a=[0-9A-Za-z]*;\ /i;

  for (i = 0; i < numLines; i++) {
    var line = lines[i];
    if (regex.test(line)) {
      let n = line.replace(/^.*SESSIDe08a=([^;]+);[.]+$/, "$1");
      let l = n.replace(/^.*SESSIDe08a=/, "");
      let a = l.split(" ");
      let final = a[0].replace(";", "");

      output = final;
      break; // You still need to end the loop
    }
  }
} catch (e) {
  console.error(err);
  process.exit(1);
}

If you have a recent version of Node, you should be able to await in the top level, otherwise you will need to wrap it in an async function.