Skip to content
30 changes: 23 additions & 7 deletions docs/runtime/child-process.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,29 @@ console.log(text); // => "1.3.3\n"

Configure the output stream by passing one of the following values to `stdout/stderr`:

| Value | Description |
| ------------ | --------------------------------------------------------------------------------------------------- |
| `"pipe"` | **Default for `stdout`.** Pipe the output to a `ReadableStream` on the returned `Subprocess` object |
| `"inherit"` | **Default for `stderr`.** Inherit from the parent process |
| `"ignore"` | Discard the output |
| `Bun.file()` | Write to the specified file |
| `number` | Write to the file with the given file descriptor |
| Value | Description |
| ---------------- | --------------------------------------------------------------------------------------------------- |
| `"pipe"` | **Default for `stdout`.** Pipe the output to a `ReadableStream` on the returned `Subprocess` object |
| `"inherit"` | **Default for `stderr`.** Inherit from the parent process |
| `"ignore"` | Discard the output |
| `Bun.file(path)` | Write to the file at that path. Bun creates the file if it does not exist and replaces its content |
| `number` | Write to the file with the given file descriptor. Bun does not create or truncate the file |

Bun opens a `Bun.file(path)` and empties it before the command starts. If the command cannot start, the file can already be empty. When the same path is also `stdin`, the command reads an empty file. To filter a file in place, pass `stdin: await Bun.file(path).bytes()`.

To append to a file, or to keep its content, open the file and pass the file descriptor. To collect `stdout` and `stderr` in one file, pass the same file descriptor to both.

```ts
import { closeSync, openSync } from "node:fs";

const fd = openSync("build.log", "a"); // "a" appends. "w" replaces the content.
try {
const proc = Bun.spawn(["bun", "--version"], { stdout: fd, stderr: fd });
await proc.exited;
} finally {
closeSync(fd);
}
```

## Exit handling

Expand Down
9 changes: 6 additions & 3 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7819,7 +7819,8 @@ declare module "bun" {
* - `"ignore"`, `null`: The process has no standard output/error
* - `"inherit"`: The process inherits the standard output/error of the current process
* - `ArrayBufferView`: The process writes to the preallocated buffer. Not implemented.
* - `number`: The process writes to the file descriptor
* - `Bun.file(path)`: The process writes to the file at that path. Bun creates the file if it does not exist and empties it before the process starts. To append, to keep the content, or to send stdout and stderr to one file, open the file and pass the file descriptor. To filter a file in place, pass `stdin: await Bun.file(path).bytes()`.
* - `number`: The process writes to the file descriptor. Bun does not create or truncate the file.
*
* At indices >= 3, `"socket-fd"` (POSIX only) is also accepted:
* creates a socketpair like `"pipe"`, but the parent-end fd exposed
Expand Down Expand Up @@ -7852,7 +7853,8 @@ declare module "bun" {
* - `"ignore"`, `null`: The process has no standard output/error
* - `"inherit"`: The process inherits the standard output/error of the current process
* - `ArrayBufferView`: The process writes to the preallocated buffer. Not implemented.
* - `number`: The process writes to the file descriptor
* - `Bun.file(path)`: The process writes to the file at that path. Bun creates the file if it does not exist and empties it before the process starts. To append, to keep the content, or to send stdout and stderr to one file, open the file and pass the file descriptor. To filter a file in place, pass `stdin: await Bun.file(path).bytes()`.
* - `number`: The process writes to the file descriptor. Bun does not create or truncate the file.
*
* @default "pipe"
*/
Expand All @@ -7864,7 +7866,8 @@ declare module "bun" {
* - `"ignore"`, `null`: The process has no standard output/error
* - `"inherit"`: The process inherits the standard output/error of the current process
* - `ArrayBufferView`: The process writes to the preallocated buffer. Not implemented.
* - `number`: The process writes to the file descriptor
* - `Bun.file(path)`: The process writes to the file at that path. Bun creates the file if it does not exist and empties it before the process starts. To append, to keep the content, or to send stdout and stderr to one file, open the file and pass the file descriptor. To filter a file in place, pass `stdin: await Bun.file(path).bytes()`.
* - `number`: The process writes to the file descriptor. Bun does not create or truncate the file.
*
* @default "inherit" for `spawn`
* "pipe" for `spawnSync`
Expand Down
2 changes: 1 addition & 1 deletion src/libuv_sys/libuv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2395,7 +2395,7 @@ pub mod O {
}

/// Convert from internal `bun.O` flags to libuv/Windows flags.
pub fn from_bun_o(c_flags: i32) -> i32 {
pub const fn from_bun_o(c_flags: i32) -> i32 {
let mut flags: i32 = 0;
if c_flags & bun_o::WRONLY != 0 {
flags |= WRONLY;
Expand Down
90 changes: 61 additions & 29 deletions src/runtime/shell/states/Cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -780,17 +780,27 @@ impl Cmd {
// `get_body_value` is `&self`.
let req = unsafe { &*req };
req.get_body_value().to_blob_if_possible();
let body = req.get_body_value().use_as_any_blob();
// As `Stdio::Path` it would get the flags of `Bun.spawn`, not of the operator.
if let Some(path) = file_path(&body) {
let mut path_buf = path.to_vec();
path_buf.push(0);
let path = bun_core::ZStr::from_buf(&path_buf, path_buf.len() - 1);
return Ok(Self::open_redirect_path(interp, this, stdio, flags, path));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
}
let mut body = Some(body);
let mut next_blob = || {
body.take()
.unwrap_or_else(|| req.get_body_value().use_as_any_blob())
};
if flags.stdin() {
let b = req.get_body_value().use_as_any_blob();
stdio[STDIN_NO].extract_blob(global, b, STDIN_NO as i32)?;
stdio[STDIN_NO].extract_blob(global, next_blob(), STDIN_NO as i32)?;
}
if flags.stdout() {
let b = req.get_body_value().use_as_any_blob();
stdio[STDOUT_NO].extract_blob(global, b, STDOUT_NO as i32)?;
stdio[STDOUT_NO].extract_blob(global, next_blob(), STDOUT_NO as i32)?;
}
if flags.stderr() {
let b = req.get_body_value().use_as_any_blob();
stdio[STDERR_NO].extract_blob(global, b, STDERR_NO as i32)?;
stdio[STDERR_NO].extract_blob(global, next_blob(), STDERR_NO as i32)?;
}
} else {
return Err(global.throw(format_args!(
Expand Down Expand Up @@ -826,34 +836,42 @@ impl Cmd {
};
let path = bun_core::ZStr::from_buf(&path_buf, path_buf.len() - 1);
log!("Expanded Redirect: {}\n", bstr::BStr::new(path.as_bytes()));
let cwd_fd = interp.as_cmd(this).base.shell().cwd_fd;
let redirfd = match crate::shell::interpreter::shell_openat(
cwd_fd,
path,
flags.to_flags(),
0o666,
) {
Ok(f) => f,
Err(e) => {
let sys_err = e.to_shell_system_error();
return Ok(Some(Builtin::cmd_write_failing_error(
interp,
this,
format_args!(
"bun: {}: {}",
sys_err.message,
bstr::BStr::new(path.as_bytes())
),
)));
}
};
interp.as_cmd_mut(this).redirection_fd = Some(CowFd::init(redirfd));
set_stdio_from_redirect(stdio, flags, redirfd);
return Ok(Self::open_redirect_path(interp, this, stdio, flags, path));
}
}
Ok(None)
}

/// Opens `path` with the flags of the redirect operator. `Some` is the queued error write.
fn open_redirect_path(
interp: &Interpreter,
this: NodeId,
stdio: &mut [Stdio; 3],
flags: ast::RedirectFlags,
path: &bun_core::ZStr,
) -> Option<Yield> {
let cwd_fd = interp.as_cmd(this).base.shell().cwd_fd;
let redirfd =
match crate::shell::interpreter::shell_openat(cwd_fd, path, flags.to_flags(), 0o666) {
Ok(f) => f,
Err(e) => {
let sys_err = e.to_shell_system_error();
return Some(Builtin::cmd_write_failing_error(
interp,
this,
format_args!(
"bun: {}: {}",
sys_err.message,
bstr::BStr::new(path.as_bytes())
),
));
}
};
interp.as_cmd_mut(this).redirection_fd = Some(CowFd::init(redirfd));
set_stdio_from_redirect(stdio, flags, redirfd);
None
}

/// Called by `Builtin::done` / subprocess exit handler.
pub(crate) fn on_exec_done(interp: &Interpreter, this: NodeId, exit_code: ExitCode) -> Yield {
log!("Cmd {} execDone exit={}", this, exit_code);
Expand Down Expand Up @@ -1123,6 +1141,20 @@ fn is_assignment_word(atom: &ast::Atom) -> bool {
.all(|&b| b.is_ascii_alphanumeric() || b == b'_')
}

/// The path of a blob that `Stdio::extract_blob` lowers to `Stdio::Path`.
fn file_path(blob: &crate::webcore::blob::Any) -> Option<&[u8]> {
if !blob.needs_to_read_file() {
return None;
}
let crate::webcore::blob::store::Data::File(file) = &blob.store()?.data else {
return None;
};
match &file.pathlike {
crate::node::PathOrFileDescriptor::Path(path) => Some(path.slice()),
crate::node::PathOrFileDescriptor::Fd(_) => None,
}
}

fn set_stdio_from_redirect(stdio: &mut [Stdio; 3], flags: ast::RedirectFlags, fd: bun_sys::Fd) {
if flags.stdin() {
stdio[0] = Stdio::Fd(fd);
Expand Down
3 changes: 3 additions & 0 deletions src/runtime/shell/subproc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,9 @@ impl ShellSubprocess {
true
};

// `${Bun.file(path)}` is a path word, and `Cmd` opens a `Response` over a file itself.
debug_assert!(!stdio_guard.iter().any(|s| matches!(s, Stdio::Path(_))));

// Hoist asSpawnOption results so a later one failing doesn't strand an earlier
// Windows *uv.Pipe in an unbound temporary inside the struct initializer.
// `mut` only for the Windows-only `.deinit()` rollback below.
Expand Down
101 changes: 50 additions & 51 deletions src/spawn/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2083,11 +2083,6 @@ mod spawn_process_body {
for fd_i in 0..3usize {
let pipe_flags = uv::UV_CREATE_PIPE | uv::UV_READABLE_PIPE | uv::UV_WRITABLE_PIPE;
let stdio: &mut uv::uv_stdio_container_t = &mut stdio_containers[fd_i];
let flag: c_int = if fd_i == 0 {
uv::O::RDONLY
} else {
uv::O::WRONLY
};

let mut treat_as_dup: bool = false;

Expand Down Expand Up @@ -2117,36 +2112,20 @@ mod spawn_process_body {
stdio.flags = uv::UV_IGNORE;
}
WindowsStdio::Path(path) => {
let mut req = uv::fs_t::uninitialized();
// Cleanup is via manual calls at each exit path, so `?` here
// would leak any fds opened by earlier loop iterations.
let path_z = match bun_sys::to_posix_path(path) {
Ok(p) => p,
let fd = match open_path_slot(loop_, path, fd_i) {
Comment thread
robobun marked this conversation as resolved.
Resolved
Ok(Ok(fd)) => fd,
Ok(Err(err)) => {
cleanup_uv_files(&uv_files_to_close, loop_);
return Ok(Err(err));
}
Err(e) => {
cleanup_uv_files(&uv_files_to_close, loop_);
return Err(crate::Error::Sys(e));
return Err(e);
}
};
// SAFETY: `req` is a fresh `fs_t`, `loop_` is the live uv
// loop, `path_z` is NUL-terminated and outlives the call
// (sync — no callback).
let rc = unsafe {
uv::uv_fs_open(
loop_,
&mut req,
path_z.as_ptr(),
flag | uv::O::CREAT,
0o644,
None,
)
};
req.deinit();
if let Some(err) = rc.to_error(bun_sys::Tag::open) {
cleanup_uv_files(&uv_files_to_close, loop_);
return Ok(Err(err));
}
stdio.flags = uv::UV_INHERIT_FD;
let fd = rc.int();
uv_files_to_close.push(fd);
stdio.data.fd = fd;
}
Expand Down Expand Up @@ -2186,7 +2165,6 @@ mod spawn_process_body {

for (i, ipc) in options.extra_fds.iter().enumerate() {
let stdio: &mut uv::uv_stdio_container_t = &mut stdio_containers[3 + i];
let flag: c_int = uv::O::RDWR;

match ipc {
WindowsStdio::Dup2(_) => panic!("TODO dup2 extra fd"),
Expand All @@ -2198,34 +2176,19 @@ mod spawn_process_body {
stdio.flags = uv::UV_IGNORE;
}
WindowsStdio::Path(path) => {
let mut req = uv::fs_t::uninitialized();
// See stdio loop above: manual cleanup on every exit path.
let path_z = match bun_sys::to_posix_path(path) {
Ok(p) => p,
let fd = match open_path_slot(loop_, path, 3 + i) {
Ok(Ok(fd)) => fd,
Ok(Err(err)) => {
cleanup_uv_files(&uv_files_to_close, loop_);
return Ok(Err(err));
}
Err(e) => {
cleanup_uv_files(&uv_files_to_close, loop_);
return Err(crate::Error::Sys(e));
return Err(e);
}
};
// SAFETY: `req` is a fresh `fs_t`, `loop_` is the live uv loop,
// `path_z` is NUL-terminated and outlives the call (sync).
let rc = unsafe {
uv::uv_fs_open(
loop_,
&mut req,
path_z.as_ptr(),
flag | uv::O::CREAT,
0o644,
None,
)
};
req.deinit();
if let Some(err) = rc.to_error(bun_sys::Tag::open) {
cleanup_uv_files(&uv_files_to_close, loop_);
return Ok(Err(err));
}
stdio.flags = uv::UV_INHERIT_FD;
let fd = rc.int();
uv_files_to_close.push(fd);
stdio.data.fd = fd;
}
Expand Down Expand Up @@ -2431,6 +2394,42 @@ mod spawn_process_body {
}
}

/// Opens the file of a `Path` stdio for child fd `slot`.
#[cfg(windows)]
fn open_path_slot(
loop_: *mut uv::uv_loop_t,
path: &[u8],
slot: usize,
) -> Result<bun_sys::Result<uv::uv_file>, crate::Error> {
let path_z = bun_sys::to_posix_path(path).map_err(crate::Error::Sys)?;
Comment thread
robobun marked this conversation as resolved.
Resolved
let open = |flags: c_int| {
let mut req = uv::fs_t::uninitialized();
// SAFETY: `req` is a fresh `fs_t`, `loop_` is the live uv loop,
// `path_z` is NUL-terminated and outlives the call (sync — no callback).
let rc =
unsafe { uv::uv_fs_open(loop_, &mut req, path_z.as_ptr(), flags, 0o644, None) };
req.deinit();
rc
};
let flags = uv::O::from_bun_o(bun_spawn_sys::path_slot_open_flags(slot));
let rc = open(flags);
// CREATE_ALWAYS refuses a hidden file (https://github.com/oven-sh/bun/issues/6820).
if flags & uv::O::TRUNC != 0 && rc.errno() == Some(bun_sys::E::EPERM) {
let in_place = open(flags & !(uv::O::CREAT | uv::O::TRUNC));
if !in_place.is_err() {
let fd = Fd::from_uv(in_place.int());
if bun_sys::ftruncate(fd, 0).is_ok() {
return Ok(Ok(in_place.int()));
}
bun_io::Closer::close(fd, loop_);
}
}
Ok(match rc.to_error(bun_sys::Tag::open) {
Some(err) => Err(err),
None => Ok(rc.int()),
})
}

pub mod sync {
use super::*;
// `Options.windows` is `WindowsOptions` on Windows; surface it under the
Expand Down
2 changes: 1 addition & 1 deletion src/spawn_sys/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,5 +190,5 @@ pub use spawn_process::spawn_process_posix;
pub use spawn_process::uv_getrusage;
pub use spawn_process::{
Dup2, ExtraPipe, PidT, PosixSpawnOptions, PosixSpawnResult, PosixStdio, Rusage, RusageFields,
StdioKind, rusage_zeroed,
StdioKind, path_slot_open_flags, rusage_zeroed,
};
Loading
Loading