创建子进程
概念 跳转到标题
- Deno 能够通过 Deno.Command 生成子进程。
- 需要
--allow-run
权限才能生成子进程。 - 生成的子进程不在安全沙箱中运行。
- 通过 stdin、stdout 和 stderr 流与子进程通信。
简单示例 跳转到标题
此示例等同于从命令行运行 echo "Hello from Deno!"
。
subprocess_simple.ts
// define command used to create the subprocess
const command = new Deno.Command("echo", {
args: [
"Hello from Deno!",
],
});
// create subprocess and collect output
const { code, stdout, stderr } = await command.output();
console.assert(code === 0);
console.log(new TextDecoder().decode(stdout));
console.log(new TextDecoder().decode(stderr));
运行它
$ deno run --allow-run=echo ./subprocess_simple.ts
Hello from Deno!
安全性 跳转到标题
创建子进程需要 --allow-run
权限。请注意,子进程不在 Deno 沙箱中运行,因此具有与您自己从命令行运行命令相同的权限。
与子进程通信 跳转到标题
默认情况下,当您使用 Deno.Command()
时,子进程会继承父进程的 stdin
、stdout
和 stderr
。如果您想与启动的子进程通信,则必须使用 "piped"
选项。
管道输出到文件 跳转到标题
此示例等同于在 bash 中运行 yes &> ./process_output
。
subprocess_piping_to_files.ts
import {
mergeReadableStreams,
} from "jsr:@std/streams@1.0.0-rc.4/merge-readable-streams";
// 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=yes --allow-read=. --allow-write=. ./subprocess_piping_to_file.ts