跳至主要内容

创建子进程

概念

  • Deno 可以通过 Deno.Command 生成子进程。
  • 生成子进程需要 --allow-run 权限。
  • 生成的子进程不会在安全沙箱中运行。
  • 可以通过 stdinstdoutstderr 流与子进程进行通信。

简单示例

此示例等同于从命令行运行 'echo hello'

/**
* subprocess_simple.ts
*/

// define command used to create the subprocess
const command = new Deno.Command(Deno.execPath(), {
args: [
"eval",
"console.log('hello'); console.error('world')",
],
});

// create subprocess and collect output
const { code, stdout, stderr } = await command.output();

console.assert(code === 0);
console.assert("world\n" === new TextDecoder().decode(stderr));
console.log(new TextDecoder().decode(stdout));

运行它

$ deno run --allow-run --allow-read ./subprocess_simple.ts
hello

安全

创建子进程需要 --allow-run 权限。请注意,子进程不会在 Deno 沙箱中运行,因此它们具有与您从命令行自己运行命令相同的权限。

与子进程通信

默认情况下,当您使用 Deno.Command() 时,子进程会继承父进程的 stdinstdoutstderr。如果您想与启动的子进程通信,则必须使用 "piped" 选项。

管道到文件

此示例等效于在 bash 中运行 yes &> ./process_output

/**
* subprocess_piping_to_file.ts
*/

import {
mergeReadableStreams,
} from "https://deno.land/[email protected]/streams/merge_readable_streams.ts";

// create the file to attach the process to
const file = await Deno.open("./process_output.txt", {
read: true,
write: true,
create: true,
});

// start the process
const command = new Deno.Command("yes", {
stdout: "piped",
stderr: "piped",
});

const process = command.spawn();

// example of combining stdout and stderr while sending to a file
const joined = mergeReadableStreams(
process.stdout,
process.stderr,
);

// returns a promise that resolves when the process is killed/closed
joined.pipeTo(file.writable).then(() => console.log("pipe join done"));

// manually stop process "yes" will never end on its own
setTimeout(() => {
process.kill();
}, 100);

运行它

$ deno run --allow-run --allow-read --allow-write ./subprocess_piping_to_file.ts