Deno:如何在子进程完成之前运行shell命令并读取输出?

bxjv4tth  于 12个月前  发布在  Shell
关注(0)|答案(1)|浏览(108)

如何启动一个子进程(通过shell)并在子进程返回之前读取其输出?
我正在通过Mac终端使用以下命令启动Google Chrome:/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222 --no-first-run --no-default-browser-check --user-data-dir=$(mktemp -d -t 'chrome-remote_data_dir')这工作得很好,但该过程不会结束/返回,直到我完成与浏览器.但是,一旦启动,它就会将以下内容打印到控制台:“DevTools在ws://www.example.com上侦听127.0.0.1:9222/devtools/browser/d43342be-66bc-41d4-b591-a7ee22d1c528“
我要刮一下。我可以在Deno中成功地启动它(v。1.36.3)使用:

const myCMD = `/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome`;

const p = Deno.run({
  cmd: [
    myCMD,
    "--remote-debugging-port=9222",
    "--no-first-run",
    "--no-default-browser-check",
    "--user-data-dir=$(mktemp -d -t 'chrome-remote_data_dir')",
  ],
  stdout: "piped",
  stderr: "piped",
  stdin: "piped",
});

await p.stdin.write(new TextEncoder().encode("Coming from stdin\n"));
await p.status();

但是我不能读取我需要的值,因为过程没有完成,因此输出永远不会返回。有没有办法在子进程返回之前读取它写入控制台的内容?
FYI.我使用了以下文章作为参考:https://medium.com/deno-the-complete-reference/run-shell-commands-in-deno-26c3e9b72e03

mm5n2pyu

mm5n2pyu1#

您需要从p.stdoutp.stderr读取,两者都是FsFile的示例,因此您可以使用.readable访问ReadableStream或使用FsFile.read方法

const myCMD = `/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome`;

const p = Deno.run({
  cmd: [
    myCMD,
    "--remote-debugging-port=9222",
    "--no-first-run",
    "--no-default-browser-check",
    "--user-data-dir=$(mktemp -d -t 'chrome-remote_data_dir')",
  ],
  stdout: "piped",
  stderr: "piped",
  stdin: "piped",
});

(async() => {
   for await(const chunk of p.stdout.readable) {
       console.log(chunk, new TextDecoder().decode(chunk))
   }
})();

(async() => {
    for await(const chunk of p.stderr.readable) {
        console.log(chunk, new TextDecoder().decode(chunk))
    }
})();

await p.stdin.write(new TextEncoder().encode("Coming from stdin\n"));
await p.status();

现在您将看到该过程的输出。

相关问题