Subprocesses: Spawning

For more complex usecases, we don’t simply want the output of some command. In this case, we can spawn a subprocess and interact with it using convenience methods for reading output streams.

Edit on GitHub

The Ende namespace has a unified api for interacting with the outside system called Ende.Command. With it, we can initialize some information about the command but it will not be executed immediately.

const command = new Ende.Command("ende", {
  args: [
    "fmt",
    "-",
  ],
  stdin: "piped",
  stdout: "piped"
});

In a slightly more complex case, we want to interact with a spawned process. To do this, we first need to spawn it.

const process = command.spawn();

We can now pipe the input into stdin. To do this we must first get a writer from the stream and write to it

const writer = process.stdin.getWriter();
await writer.write(new TextEncoder().encode(`console.log("hello")`));
writer.releaseLock();

We must then close stdin

await process.stdin.close();

We can now wait for the process to output the results using convenience methods

const stdout = await process.stdout.text();
console.log(stdout);

Wait for the process to complete

await process.status;

Run this example locally using the Ende CLI:

ende run --allow-run https://docs.ende.sh/examples/scripts/subprocesses_spawn.ts

Additional resources