Typorithm · medium

Bun.spawn

bun-spawn-processbunsubprocessstreamsspawn-sync
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Bun.spawn

0%

System & FFI

Bun.spawn runs a subprocess from an argv array; proc.stdout is a ReadableStream and proc.exited resolves to the exit code. Pass stdin, env, and cwd via options. Bun.spawnSync blocks and returns Buffers for simple one-shot commands.

Bun.spawn(["ls", "-la"]) launches a subprocess and returns a handle immediately; you control it with an options object carrying stdin, env, and cwd.

Output is streamed: proc.stdout is a ReadableStream, so wrap it in a Response to await .text(), and await proc.exited to get the numeric exit code once it finishes.

When you just need a quick result, Bun.spawnSync blocks until the command exits and hands back stdout and stderr as Buffers via .toString().

01

Bun.spawn takes an argv array plus { cwd, env, stdin }.

02

proc.stdout is a ReadableStream; await proc.exited for the code.

03

Bun.spawnSync blocks and returns Buffers directly.

const proc = Bun.spawn(["ls", "-la"], { cwd: "./src", env: { ...process.env } });
const out = await new Response(proc.stdout).text();
const code = await proc.exited;
const sync = Bun.spawnSync(["echo", "hi"]);
console.log(sync.stdout.toString());

Read the implementation

Connect each part of the code to the concept before you type.

1. Spawn a subprocess

Bun.spawn takes the command as an argv array and an options object for cwd, env, and stdin.

Bun.spawn(["ls", "-la"], { cwd: "./src", env: { ...process.env } })

2. Read stdout stream

proc.stdout is a ReadableStream; wrapping it in a Response lets you await .text() to collect the output.

const out = await new Response(proc.stdout).text();

3. Await the exit code

proc.exited is a promise that resolves to the numeric exit code once the process finishes.

const code = await proc.exited;

4. Synchronous spawn

Bun.spawnSync blocks until the process exits and returns its captured output directly.

const sync = Bun.spawnSync(["echo", "hi"]);

5. Sync output buffer

spawnSync gives stdout as a Buffer, so call .toString() to read it as text.

console.log(sync.stdout.toString());

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Bun.spawn: Lesson & Practice · Typorithm | ApplyDjinn