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

标签 shell google-chrome-devtools deno

如何启动子进程(通过 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://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();

但我无法读取所需的值,因为该过程未完成,因此输出永远不会返回。有没有办法在子进程返回之前读取子进程写入控制台的内容?

仅供引用...我使用以下文章作为引用:https://medium.com/deno-the-complete-reference/run-shell-commands-in-deno-26c3e9b72e03

最佳答案

您需要读取p.stdoutp.stderr,它们都是FsFile的实例。因此您可以使用 .read 访问 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();

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

关于shell - Deno:如何在子进程完成之前运行 shell 命令并读取输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77028902/

相关文章:

deno - 如何从服务器传输异步字符串

typescript - Deno(typescript) 中的 Promise { <pending> }

java - 使用 build.sh 脚本构建 Android

linux - 使用 procmail 触发应用程序在我的计算机上运行...但我遇到了障碍

javascript - 找出创建 javascript 对象的位置

http - 在 Deno 中获取远程客户端 IP 地址

python - 通过 ubuntu 应用程序运行的 Matplotlib 弃用警告

linux - 将每个目录的内容移动到一个新的子目录

ajax - 如何在测试环境中模拟失败的 XHR 调用

google-chrome - Chrome 网络计时的真正含义是什么以及影响每个计时长度的因素是什么?