从 shell 命令读取 ChildProcess 返回值

问题描述 投票:0回答:1

我正在将这个 ChildProcess 函数执行到 Nextjs API 路由中,但我无法从中读取值。

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
          }
        }

      }
    }
  );

如何读取返回的

final
值?

javascript reactjs node.js next.js child-process
1个回答
0
投票

既然有回调函数,那么返回的时候返回的是回调函数,不是向上传递的,是从

exec()
返回的。您将需要使用超出范围的变量。然而,问题是执行将继续。您将需要使用承诺。请参阅此线程,然后:

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);
}

如果您有最新版本的 Node,您应该能够在顶层

await
,否则您需要将其包装在
async
函数中。

© www.soinside.com 2019 - 2024. All rights reserved.