温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.bun.com/reference/bun/Spawn
点击访问原文链接

Bun.Spawn object | API Reference | Bun

Bun.Spawn object | API Reference | BunBuildDocsReferenceGuidesBlogDiscord/Bun/SpawnNSpawn

Search the reference...

/

BuildDocsReferenceGuidesBlogDiscord/Bun/SpawnNSpawn

namespace

Spawnnamespace Spawninterface BaseOptionsIn 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.

cwd?: string

The current working directory of the process

Defaults to process.cwd()

detached?: boolean

Run the child in a separate process group, detached from the parent.

POSIX: calls setsid() so the child starts a new session and becomes the process group leader. It can outlive the parent and receive signals independently of the parent’s terminal/process group.Windows: sets UV_PROCESS_DETACHED, allowing the child to outlive the parent and receive signals independently.

Note: stdio may keep the parent process alive. Pass stdio: ["ignore", "ignore", "ignore"] to the spawn constructor to prevent this.

env?: Recordstring, undefined | string>

The environment variables of the process

Defaults to process.env as it was when the current Bun process launched.

Changes to process.env at runtime won't automatically be reflected in the default value. For that, you can pass process.env explicitly.

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 maxBuffer limit.

// 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 ipc is 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 fetch response.

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, and stderr properties.

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
windowsHide?: boolean

If true, the subprocess will have a hidden window.

windowsVerbatimArguments?: boolean

If true, no quoting or escaping of arguments is done on Windows.

ipc(message: any,subprocess: SubprocessIn, Out, Err>,handle?: unknown): void;

When specified, Bun will open an IPC channel to the subprocess. The passed callback is called for incoming messages, and subprocess.send can send messages to the subprocess. Messages are serialized using the JSC serialize API, which allows for the same types that postMessage/structuredClone supports.

The subprocess can send and receive messages by using process.send and process.on("message"), respectively. This is the same API as what Node.js exposes when child_process.fork() is used.

Currently, this is only compatible with processes that are other bun instances.

@param subprocess

The Subprocess that received the message

onDisconnect(): void | Promisevoid>;

Called exactly once when the IPC channel between the parent and this subprocess is closed. After this runs, no further IPC messages will be delivered.

When it fires:

The child called process.disconnect() or the parent called subprocess.disconnect().The child exited for any reason (normal exit or due to a signal like SIGILL, SIGKILL, etc.).The child replaced itself with a program that does not support Bun IPC.

Notes:

This callback indicates that the pipe is closed; it is not an error by itself. Use onExit or Subprocess.exited to determine why the process ended.It may occur before or after onExit depending on timing; do not rely on ordering. Typically, if you or the child call disconnect() first, this fires before onExit; if the process exits without an explicit disconnect, either may happen first.Only runs when ipc is enabled and runs at most once per subprocess.If the child becomes a zombie (exited but not yet reaped), the IPC is already closed, and this callback will fire (or may already have fired).
const subprocess = spawn({
cmd: ["echo", "hello"],
ipc: (message) => console.log(message),
onDisconnect: () => {
console.log("IPC channel disconnected");
},
});
onExit(subprocess: SubprocessIn, Out, Err>,exitCode: null | number,signalCode: null | number,error?: ErrorLike): void | Promisevoid>;

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.spawn function returns.

A simple alternative is await subprocess.exited.

@param error

If 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 SpawnOptionsIn 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.

cwd?: string

The current working directory of the process

Defaults to process.cwd()

detached?: boolean

Run the child in a separate process group, detached from the parent.

POSIX: calls setsid() so the child starts a new session and becomes the process group leader. It can outlive the parent and receive signals independently of the parent’s terminal/process group.Windows: sets UV_PROCESS_DETACHED, allowing the child to outlive the parent and receive signals independently.

Note: stdio may keep the parent process alive. Pass stdio: ["ignore", "ignore", "ignore"] to the spawn constructor to prevent this.

env?: Recordstring, undefined | string>

The environment variables of the process

Defaults to process.env as it was when the current Bun process launched.

Changes to process.env at runtime won't automatically be reflected in the default value. For that, you can pass process.env explicitly.

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 maxBuffer limit.

// Kill the process with SIGKILL after 5 seconds
const subprocess = Bun.spawn({
cmd: ["sleep", "10"],
timeout: 5000,
killSignal: "SIGKILL",
});
lazy?: boolean

If true, stdout and stderr pipes will not automatically start reading data. Reading will only begin when you access the stdout or stderr properties.

This can improve performance when you don't need to read output immediately.

const subprocess = Bun.spawn({
cmd: ["echo", "hello"],
lazy: true, // Don't start reading stdout until accessed
});
// stdout reading hasn't started yet
await subprocess.stdout.text(); // Now reading starts
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 ipc is 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 fetch response.

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, and stderr properties.

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
terminal?: TerminalOptions | Terminal

Spawn the subprocess with a pseudo-terminal (PTY) attached.

When this option is provided:

stdin, stdout, and stderr are all connected to the terminalThe subprocess sees itself running in a real terminal (isTTY = true)Access the terminal via subprocess.terminalsubprocess.stdin, subprocess.stdout, subprocess.stderr return null

Only available on POSIX systems (Linux, macOS).

const proc = Bun.spawn(["bash"], {
terminal: {
cols: 80,
rows: 24,
data: (term, data) => console.log(data.toString()),
},
});

proc.terminal.write("echo hello\n");
await proc.exited;
proc.terminal.close();

You can also pass an existing Terminal object for reuse across multiple spawns:

const terminal = new Bun.Terminal({ ... });
const proc1 = Bun.spawn(["echo", "first"], { terminal });
await proc1.exited;
const proc2 = Bun.spawn(["echo", "second"], { terminal });
await proc2.exited;
terminal.close();
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
windowsHide?: boolean

If true, the subprocess will have a hidden window.

windowsVerbatimArguments?: boolean

If true, no quoting or escaping of arguments is done on Windows.

ipc(message: any,subprocess: SubprocessIn, Out, Err>,handle?: unknown): void;

When specified, Bun will open an IPC channel to the subprocess. The passed callback is called for incoming messages, and subprocess.send can send messages to the subprocess. Messages are serialized using the JSC serialize API, which allows for the same types that postMessage/structuredClone supports.

The subprocess can send and receive messages by using process.send and process.on("message"), respectively. This is the same API as what Node.js exposes when child_process.fork() is used.

Currently, this is only compatible with processes that are other bun instances.

@param subprocess

The Subprocess that received the message

onDisconnect(): void | Promisevoid>;

Called exactly once when the IPC channel between the parent and this subprocess is closed. After this runs, no further IPC messages will be delivered.

When it fires:

The child called process.disconnect() or the parent called subprocess.disconnect().The child exited for any reason (normal exit or due to a signal like SIGILL, SIGKILL, etc.).The child replaced itself with a program that does not support Bun IPC.

Notes:

This callback indicates that the pipe is closed; it is not an error by itself. Use onExit or Subprocess.exited to determine why the process ended.It may occur before or after onExit depending on timing; do not rely on ordering. Typically, if you or the child call disconnect() first, this fires before onExit; if the process exits without an explicit disconnect, either may happen first.Only runs when ipc is enabled and runs at most once per subprocess.If the child becomes a zombie (exited but not yet reaped), the IPC is already closed, and this callback will fire (or may already have fired).
const subprocess = spawn({
cmd: ["echo", "hello"],
ipc: (message) => console.log(message),
onDisconnect: () => {
console.log("IPC channel disconnected");
},
});
onExit(subprocess: SubprocessIn, Out, Err>,exitCode: null | number,signalCode: null | number,error?: ErrorLike): void | Promisevoid>;

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.spawn function returns.

A simple alternative is await subprocess.exited.

@param error

If 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 SpawnSyncOptionsIn 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.

cwd?: string

The current working directory of the process

Defaults to process.cwd()

detached?: boolean

Run the child in a separate process group, detached from the parent.

POSIX: calls setsid() so the child starts a new session and becomes the process group leader. It can outlive the parent and receive signals independently of the parent’s terminal/process group.Windows: sets UV_PROCESS_DETACHED, allowing the child to outlive the parent and receive signals independently.

Note: stdio may keep the parent process alive. Pass stdio: ["ignore", "ignore", "ignore"] to the spawn constructor to prevent this.

env?: Recordstring, undefined | string>

The environment variables of the process

Defaults to process.env as it was when the current Bun process launched.

Changes to process.env at runtime won't automatically be reflected in the default value. For that, you can pass process.env explicitly.

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 maxBuffer limit.

// 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 ipc is 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 fetch response.

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, and stderr properties.

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
windowsHide?: boolean

If true, the subprocess will have a hidden window.

windowsVerbatimArguments?: boolean

If true, no quoting or escaping of arguments is done on Windows.

ipc(message: any,subprocess: SubprocessIn, Out, Err>,handle?: unknown): void;

When specified, Bun will open an IPC channel to the subprocess. The passed callback is called for incoming messages, and subprocess.send can send messages to the subprocess. Messages are serialized using the JSC serialize API, which allows for the same types that postMessage/structuredClone supports.

The subprocess can send and receive messages by using process.send and process.on("message"), respectively. This is the same API as what Node.js exposes when child_process.fork() is used.

Currently, this is only compatible with processes that are other bun instances.

@param subprocess

The Subprocess that received the message

onDisconnect(): void | Promisevoid>;

Called exactly once when the IPC channel between the parent and this subprocess is closed. After this runs, no further IPC messages will be delivered.

When it fires:

The child called process.disconnect() or the parent called subprocess.disconnect().The child exited for any reason (normal exit or due to a signal like SIGILL, SIGKILL, etc.).The child replaced itself with a program that does not support Bun IPC.

Notes:

This callback indicates that the pipe is closed; it is not an error by itself. Use onExit or Subprocess.exited to determine why the process ended.It may occur before or after onExit depending on timing; do not rely on ordering. Typically, if you or the child call disconnect() first, this fires before onExit; if the process exits without an explicit disconnect, either may happen first.Only runs when ipc is enabled and runs at most once per subprocess.If the child becomes a zombie (exited but not yet reaped), the IPC is already closed, and this callback will fire (or may already have fired).
const subprocess = spawn({
cmd: ["echo", "hello"],
ipc: (message) => console.log(message),
onDisconnect: () => {
console.log("IPC channel disconnected");
},
});
onExit(subprocess: SubprocessIn, Out, Err>,exitCode: null | number,signalCode: null | number,error?: ErrorLike): void | Promisevoid>;

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.spawn function returns.

A simple alternative is await subprocess.exited.

@param error

If 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}`);
},
});
type Readable = 'pipe' | 'inherit' | 'ignore' | null | undefined | BunFile | ArrayBufferView | number

Option for stdout/stderr

type ReadableToIOX extends Readable> = X extends 'pipe' | undefined ? ReadableStreamUint8ArrayArrayBuffer>> : X extends BunFile | ArrayBufferView | number ? number : undefinedtype ReadableToSyncIOX extends Readable> = X extends 'pipe' | undefined ? Buffer : undefinedtype Writable = 'pipe' | 'inherit' | 'ignore' | null | undefined | BunFile | ArrayBufferView | number | ReadableStream | Blob | Response | Request

Option for stdin

type WritableIO = FileSink | number | undefinedtype WritableToIOX extends Writable> = X extends 'pipe' ? FileSink : X extends BunFile | ArrayBufferView | Blob | Request | Response | number ? number : undefined

Resources

ReferenceDocsGuidesDiscordMerch StoreGitHubBlog 

Toolkit

RuntimePackage managerTest runnerBundlerPackage runner

Project

Bun 1.0Bun 1.1Bun 1.2Bun 1.3RoadmapContributingLicense

Baked with ❤️ in San Francisco

We're hiring →

Bun.Spawn object | API Reference | Bun,AI智能索引,全网链接索引,智能导航,网页索引

    API documentation for namespace bun.Spawn | Bun