Создание дочернего процесса
Основные понятия
- 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".
Перенаправление в файлы
Этот пример эквивалентен выполнению yes &> ./process_output в bash.
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
© 2018–2024 the Deno authors
Licensed under the MIT License.
https://docs.deno.com/runtime/tutorials/subprocess