Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2730,9 +2730,18 @@ declare module "bun" {
/**
* Does the file exist?
*
* This returns true for regular files and FIFOs. It returns false for
* directories. A race condition can occur where the file is deleted or
* renamed after this is called but before you open it.
* For a path, this returns true for every type of file except a
* directory: regular files, FIFOs, sockets, and devices such as
* `/dev/null`. It returns false for directories. A true answer does not
* mean that the file can be read, or that a read ends. To accept only
* regular files, check `(await file.stat()).isFile()`.
*
* For a file descriptor, such as `Bun.stdin`, this returns true only for
* regular files and FIFOs. To find out what stdin is, use
* `process.stdin.isTTY` or `fs.fstatSync(0)`.
*
* A race condition can occur where the file is deleted or renamed after
* this is called but before you open it.
*
* This does a system call to check if the file exists, which can be
* slow.
Expand Down
12 changes: 9 additions & 3 deletions src/runtime/webcore/Blob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1273,11 +1273,17 @@ impl BlobExt for Blob {
return JSValue::TRUE;
}

// We say regular files and pipes exist.
let store::Data::File(file) = &store.data else {
return JSValue::FALSE;
};
JSValue::from(bun_sys::S::ISREG(file.mode) || bun_sys::S::ISFIFO(file.mode))
JSValue::from(match file.pathlike {
// `mode` is 0 until a stat succeeds.
PathOrFileDescriptor::Path(_) => file.mode != 0 && !bun_sys::S::ISDIR(file.mode),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
// Programs guard stdin reads with this, so a terminal and /dev/null answer false.
PathOrFileDescriptor::Fd(_) => {
bun_sys::S::ISREG(file.mode) || bun_sys::S::ISFIFO(file.mode)
}
})
}
fn do_write(&self, global_this: &JSGlobalObject, callframe: &CallFrame) -> JsResult<JSValue> {
let cx = global_this.js_thread_of_caller(callframe);
Expand Down Expand Up @@ -1353,7 +1359,7 @@ impl BlobExt for Blob {
}
}

// This mostly means 'can it be read?'
// For a path, true does not mean that a read succeeds.
fn get_exists(&self, global_this: &JSGlobalObject, callframe: &CallFrame) -> JsResult<JSValue> {
if self.is_s3() {
return crate::webcore::s3_file::S3BlobStatTask::exists(
Expand Down
84 changes: 81 additions & 3 deletions test/js/bun/util/bun-file-exists.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { write } from "bun";
import { expect, test } from "bun:test";
import { unlinkSync } from "fs";
import { tmpdir } from "os";
import { describe, expect, test } from "bun:test";
import { closeSync, constants, openSync, unlinkSync } from "fs";
import { bunEnv, bunExe, isWindows, tempDir } from "harness";
import { mkfifo } from "mkfifo";
import { devNull, tmpdir } from "os";
import { join } from "path";
test("bun-file-exists", async () => {
expect(await Bun.file(import.meta.path).exists()).toBeTrue();
Expand All @@ -18,3 +20,79 @@ test("bun-file-exists", async () => {
unlinkSync(temp);
expect(await Bun.file(temp).exists()).toBeFalse();
});

test("exists() is true for a path to the null device", async () => {
expect(await Bun.file(devNull).exists()).toBeTrue();
});

test("exists() on a file descriptor is true for a regular file, false for the null device", async () => {
const regular = openSync(import.meta.path, "r");
const nullDevice = openSync(devNull, "r");
try {
expect({
regular: await Bun.file(regular).exists(),
nullDevice: await Bun.file(nullDevice).exists(),
}).toEqual({ regular: true, nullDevice: false });
} finally {
closeSync(regular);
closeSync(nullDevice);
}
});

describe.skipIf(isWindows)("exists() on a file that is not a regular file", () => {
test("a path is true for a FIFO and a socket, false for a directory", async () => {
using dir = tempDir("bun-file-exists", { "regular": "hello" });
const root = String(dir);
mkfifo(join(root, "fifo"));
using listener = Bun.listen({ unix: join(root, "socket"), socket: { data() {} } });

expect({
regular: await Bun.file(join(root, "regular")).exists(),
fifo: await Bun.file(join(root, "fifo")).exists(),
socket: await Bun.file(join(root, "socket")).exists(),
directory: await Bun.file(root).exists(),
missing: await Bun.file(join(root, "missing")).exists(),
}).toEqual({
regular: true,
fifo: true,
socket: true,
directory: false,
missing: false,
});
});

test("a file descriptor for a FIFO is true", async () => {
using dir = tempDir("bun-file-exists-fifo", {});
const path = join(String(dir), "fifo");
mkfifo(path);
const fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
try {
expect(await Bun.file(fd).exists()).toBeTrue();
} finally {
closeSync(fd);
}
});

// Programs read stdin only if Bun.stdin.exists() is true. With stdin from /dev/null there is nothing to read.
test("Bun.stdin from /dev/null stays false", async () => {
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`console.log(JSON.stringify({
characterDevice: require("fs").fstatSync(0).isCharacterDevice(),
stdin: await Bun.stdin.exists(),
fd: await Bun.file(0).exists(),
}));`,
],
env: bunEnv,
stdin: "ignore",
stdout: "pipe",
stderr: "inherit",
});
const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]);

expect(JSON.parse(stdout)).toEqual({ characterDevice: true, stdin: false, fd: false });
expect(exitCode).toBe(0);
});
Comment thread
robobun marked this conversation as resolved.
Resolved
});
Loading