Runtime APIs

Run child processes

Start another program with Bun.spawn, read its output, and handle its exit code without building a shell command string.

8 minute lesson

~~~

Use Bun.spawn() when your program needs to run another executable.

For example, ask Git for its version:

const process = Bun.spawn(['git', '--version'])
const output = await process.stdout.text()
const exitCode = await process.exited

console.log(output.trim())
console.log(`Exit code: ${exitCode}`)

Bun.spawn() starts the process without blocking the JavaScript event loop. process.exited resolves when the child finishes.

Check the exit code before trusting the output:

const process = Bun.spawn(['git', 'status', '--short'], {
  stderr: 'pipe',
})

const [exitCode, output, error] = await Promise.all([
  process.exited,
  process.stdout.text(),
  process.stderr.text(),
])

if (exitCode !== 0) {
  throw new Error(error.trim())
}

console.log(output)

Pass the command as an array. Each argument stays separate, so spaces inside one value do not become new shell syntax.

Avoid joining user input into a command string. A shell interprets characters such as ;, |, and $, which can turn untrusted text into a second command.

For long-running servers and applications, prefer asynchronous Bun.spawn(). Bun.spawnSync() blocks the current process and fits short command-line tasks where that behavior is intentional.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →