Creating a subprocess

Concepts

  • Deno is capable of spawning a subprocess via Deno.run.
  • --allow-run permission is required to spawn a subprocess.
  • Spawned subprocesses do not run in a security sandbox.
  • Communicate with the subprocess via the stdin, stdout and stderr streams.

Simple example

This example is the equivalent of running 'echo hello' from the command line.

  1. /**
  2. * subprocess_simple.ts
  3. */
  4. // create subprocess
  5. const p = Deno.run({
  6. cmd: ["echo", "hello"],
  7. });
  8. // await its completion
  9. await p.status();

Run it:

  1. $ deno run --allow-run ./subprocess_simple.ts
  2. hello

Security

The --allow-run permission is required for creation of a subprocess. Be aware that subprocesses are not run in a Deno sandbox and therefore have the same permissions as if you were to run the command from the command line yourself.

Communicating with subprocesses

By default when you use Deno.run() the subprocess inherits stdin, stdout and stderr of the parent process. If you want to communicate with started subprocess you can use "piped" option.

  1. /**
  2. * subprocess.ts
  3. */
  4. const fileNames = Deno.args;
  5. const p = Deno.run({
  6. cmd: [
  7. "deno",
  8. "run",
  9. "--allow-read",
  10. "https://deno.land/std@$STD_VERSION/examples/cat.ts",
  11. ...fileNames,
  12. ],
  13. stdout: "piped",
  14. stderr: "piped",
  15. });
  16. const { code } = await p.status();
  17. if (code === 0) {
  18. const rawOutput = await p.output();
  19. await Deno.stdout.write(rawOutput);
  20. } else {
  21. const rawError = await p.stderrOutput();
  22. const errorString = new TextDecoder().decode(rawError);
  23. console.log(errorString);
  24. }
  25. Deno.exit(code);

When you run it:

  1. $ deno run --allow-run ./subprocess.ts <somefile>
  2. [file content]
  3. $ deno run --allow-run ./subprocess.ts non_existent_file.md
  4. Uncaught NotFound: No such file or directory (os error 2)
  5. at DenoError (deno/js/errors.ts:22:5)
  6. at maybeError (deno/js/errors.ts:41:12)
  7. at handleAsyncMsgFromRust (deno/js/dispatch.ts:27:17)