Spawn a new process
function
spawn
Spawn a new process
const {stdout} = Bun.spawn(["echo", "hello"]);
const text = await readableStreamToText(stdout);
console.log(text); // "hello\n"
Internally, this uses posix_spawn(2)
The command to run
The first argument will be resolved to an absolute executable path. It must be a file, not a directory.
If you explicitly set PATH in env, that PATH will be used to resolve the executable instead of the default PATH.
To check if the command exists before running it, use Bun.which(bin).
Referenced types
interface OptionsObject<In extends Writable, Out extends Readable, Err extends Readable>
- argv0?: string
Path to the executable to run in the subprocess. This defaults to
cmds[0].One use-case for this is for applications which wrap other applications or to simulate a symlink.
- env?: Record<string, undefined | string>
The environment variables of the process
Defaults to
process.envas it was when the current Bun process launched.Changes to
process.envat runtime won't automatically be reflected in the default value. For that, you can passprocess.envexplicitly. - killSignal?: string | number
The signal to use when killing the process after a timeout, when the AbortSignal is aborted, or when the process goes over the
maxBufferlimit.// Kill the process with SIGKILL after 5 seconds const subprocess = Bun.spawn({ cmd: ["sleep", "10"], timeout: 5000, killSignal: "SIGKILL", }); - maxBuffer?: number
The maximum number of bytes the process may output. If the process goes over this limit, it is killed with signal
killSignal(defaults to SIGTERM). - serialization?: 'json' | 'advanced'
The serialization format to use for IPC messages. Defaults to
"advanced".To communicate with Node.js processes, use
"json".When
ipcis not specified, this is ignored. - signal?: AbortSignal
An AbortSignal that can be used to abort the subprocess.
This is useful for aborting a subprocess when some other part of the program is aborted, such as a
fetchresponse.If the signal is aborted, the process will be killed with the signal specified by
killSignal(defaults to SIGTERM).const controller = new AbortController(); const { signal } = controller; const start = performance.now(); const subprocess = Bun.spawn({ cmd: ["sleep", "100"], signal, }); await Bun.sleep(1); controller.abort(); await subprocess.exited; const end = performance.now(); console.log(end - start); // 1ms instead of 101ms - stderr?: Err
The file descriptor for the standard error. It may be:
"pipe",undefined: The process will have a ReadableStream for standard output/error"ignore",null: The process will have no standard output/error"inherit": The process will inherit the standard output/error of the current processArrayBufferView: The process write to the preallocated buffer. Not implemented.number: The process will write to the file descriptor
- stdin?: In
The file descriptor for the standard input. It may be:
"ignore",null,undefined: The process will have no standard input"pipe": The process will have a new FileSink for standard input"inherit": The process will inherit the standard input of the current processArrayBufferView,Blob: The process will read from the buffernumber: The process will read from the file descriptor
- stdio?: [In, Out, Err, ...Readable[]]
The standard file descriptors of the process, in the form [stdin, stdout, stderr]. This overrides the
stdin,stdout, andstderrproperties.For stdin you may pass:
"ignore",null,undefined: The process will have no standard input (default)"pipe": The process will have a new FileSink for standard input"inherit": The process will inherit the standard input of the current processArrayBufferView,Blob,Bun.file(),Response,Request: The process will read from buffer/stream.number: The process will read from the file descriptor
For stdout and stdin you may pass:
"pipe",undefined: The process will have a ReadableStream for standard output/error"ignore",null: The process will have no standard output/error"inherit": The process will inherit the standard output/error of the current processArrayBufferView: The process write to the preallocated buffer. Not implemented.number: The process will write to the file descriptor
- stdout?: Out
The file descriptor for the standard output. It may be:
"pipe",undefined: The process will have a ReadableStream for standard output/error"ignore",null: The process will have no standard output/error"inherit": The process will inherit the standard output/error of the current processArrayBufferView: The process write to the preallocated buffer. Not implemented.number: The process will write to the file descriptor
- timeout?: number
The maximum amount of time the process is allowed to run in milliseconds.
If the timeout is reached, the process will be killed with the signal specified by
killSignal(defaults to SIGTERM).// Kill the process after 5 seconds const subprocess = Bun.spawn({ cmd: ["sleep", "10"], timeout: 5000, }); await subprocess.exited; // Will resolve after 5 seconds - ipc(message: any,handle?: unknown): void;
When specified, Bun will open an IPC channel to the subprocess. The passed callback is called for incoming messages, and
subprocess.sendcan send messages to the subprocess. Messages are serialized using the JSC serialize API, which allows for the same types thatpostMessage/structuredClonesupports.The subprocess can send and receive messages by using
process.sendandprocess.on("message"), respectively. This is the same API as what Node.js exposes whenchild_process.fork()is used.Currently, this is only compatible with processes that are other
buninstances.@param subprocessThe Subprocess that received the message
- exitCode: null | number,signalCode: null | number,): void | Promise<void>;
Callback that runs when the Subprocess exits
This is called even if the process exits with a non-zero exit code.
Warning: this may run before the
Bun.spawnfunction returns.A simple alternative is
await subprocess.exited.@param errorIf an error occurred in the call to waitpid2, this will be the error.
const subprocess = spawn({ cmd: ["echo", "hello"], onExit: (subprocess, code) => { console.log(`Process exited with code ${code}`); }, });
interface Subprocess<In extends SpawnOptions.Writable = SpawnOptions.Writable, Out extends SpawnOptions.Readable = SpawnOptions.Readable, Err extends SpawnOptions.Readable = SpawnOptions.Readable>
A process created by Bun.spawn.
This type accepts 3 optional type parameters which correspond to the stdio array from the options object. Instead of specifying these, you should use one of the following utility types instead:
- ReadableSubprocess (any, pipe, pipe)
- WritableSubprocess (pipe, any, any)
- PipedSubprocess (pipe, pipe, pipe)
- NullSubprocess (ignore, ignore, ignore)
- readonly exitCode: null | number
Synchronously get the exit code of the process
If the process hasn't exited yet, this will return
null - readonly exited: Promise<number>
The exit code of the process
The promise will resolve when the process exits
- readonly pid: number
The process ID of the child process
const { pid } = Bun.spawn({ cmd: ["echo", "hello"] }); console.log(pid); // 1234 - readonly readable: ReadableToIO<Out>
This returns the same value as Subprocess.stdout
It exists for compatibility with ReadableStream.pipeThrough
- readonly signalCode: null | Signals
Synchronously get the signal code of the process
If the process never sent a signal code, this will return
nullTo receive signal code changes, use the
onExitcallback.If the signal code is unknown, it will return the original signal code number, but that case should essentially never happen.
- readonly stdio: [null, null, null, ...number[]]
Access extra file descriptors passed to the
stdiooption in the options object. Disconnect the IPC channel to the subprocess. This is only supported if the subprocess was created with the
ipcoption.- @param exitCode
The exitCode to send to the process
This method will tell Bun to wait for this process to exit after you already called
unref().Before shutting down, Bun will wait for all subprocesses to exit by default
Get the resource usage information of the process (max RSS, CPU time, etc)
Only available after the process has exited
If the process hasn't exited yet, this will return
undefined- send(message: any): void;
Send a message to the subprocess. This is only supported if the subprocess was created with the
ipcoption, and is another instance ofbun.Messages are serialized using the JSC serialize API, which allows for the same types that
postMessage/structuredClonesupports. Before shutting down, Bun will wait for all subprocesses to exit by default
This method will tell Bun to not wait for this process to exit before shutting down.