如何在 Deno 中获取命令的输出?

How to get the output of a command in Deno?

例如,假设我有以下代码:

Deno.run({cmd: ['echo', 'hello']})

如何收集 hello 命令的输出?

Deno.run returns Deno.Process 的实例。使用方法 .output() 获取缓冲输出。 如果您想阅读内容,请不要忘记将 "piped" 传递给 stdout/stderr 选项。

const cmd = Deno.run({
  cmd: ["echo", "hello"], 
  stdout: "piped",
  stderr: "piped"
});

const output = await cmd.output() // "piped" must be set

cmd.close(); // Don't forget to close it

.output() returns 解析为 Uint8ArrayPromise 因此,如果您希望输出为 UTF-8 字符串,则需要使用 TextDecoder

const outStr = new TextDecoder().decode(output); // hello