fs

Read, write, and manage files in the sandbox file system.

The module works in bytes and web streams. Files are read as Uint8Arrays (or strings with readTextFile) and written from Uint8Arrays or ReadableStreams. Blob and File are standard globals; pass bytes to a new Blob/File when you need one, or write a Blob/File by streaming it with writeFile.

Path Rules#

All paths must be absolute and are rooted at /:

  1. Absolute paths only - Every path must start with /
  2. Root is / - The root directory is represented by / only
  3. No relative paths - Paths without a leading / are invalid
  4. No directory traversal - . and .. are invalid
  5. No trailing slash - /scripts/ is invalid (except root /)

Usage Examples#

Reading and writing#

import fs from "fs";

await fs.writeFile("/hello.txt", new TextEncoder().encode("Hello"));
const bytes = await fs.readFile("/hello.txt");
console.log(new TextDecoder().decode(bytes));

Text files#

import fs from "fs";

await fs.writeTextFile("/hello.txt", "Hello, World!");
console.log(await fs.readTextFile("/hello.txt"));

Streaming#

import fs from "fs";

const res = await fetch("https://example.com/data.bin");
await fs.writeFile("/data.bin", res.body);

const file = await fs.open("/data.bin");
for await (const chunk of file.readable) {
  console.log("chunk", chunk.length);
}

Directory listing#

import fs from "fs";

for await (const entry of fs.readDir("/")) {
  console.log(entry.name, entry.isDir ? "(dir)" : "(file)");
}

Enums

ErrorCodes

Error codes used by FsError.

Compare against the code property of a thrown error: err.code === fs.ErrorCodes.NotExist.

Member Description
Invalid

Invalid path or parameters

Exist

File or directory already exists

NotExist

File or directory does not exist

Closed

Operation on a closed file

QuotaExceeded

Storage quota exceeded

SeekMode

Reference point for FsFile.seek, used as the whence argument.

Member Description
Start

Offset from the beginning of the file

Current

Offset from the current position

End

Offset from the end of the file

Functions

isValidPath

isValidPath(name)

Checks whether a path is valid for this module without performing any I/O.

Parameters

Name Type Description
name string

Path to check

Returns

boolean — True if the path is valid

Example

fs.isValidPath("/scripts/main.js"); // true
fs.isValidPath("./main.js"); // false - relative paths are invalid

open

open(name)

Opens a file for reading, writing, and seeking.

Opening a directory is invalid; use readDir to list one. Close the handle with FsFile.close when you are done.

Parameters

Name Type Description
name string

File path

Returns

Promise.<FsFile> — Open file handle

Throws

  • PathError — If the path is invalid, does not exist, or is a directory

Example

const file = await fs.open("/document.txt");
try {
  const info = await file.stat();
  console.log("Size:", info.size);
} finally {
  await file.close();
}

stat

stat(name)

Gets file metadata.

Parameters

Name Type Description
name string

File path

Returns

Promise.<FileInfo> — File information

Throws

  • PathError — If the path is invalid or the file does not exist

Example

const info = await fs.stat("/file.txt");
console.log("Size:", info.size);

readFile

readFile(name)

Reads the entire file as bytes.

Parameters

Name Type Description
name string

File path

Returns

Promise.<Uint8Array> — File contents

Throws

  • PathError — If the path is invalid, the file does not exist, or it is a directory

Example

const bytes = await fs.readFile("/hello.txt");
console.log(new TextDecoder().decode(bytes));

readTextFile

readTextFile(name)

Reads the entire file as a UTF-8 string.

Parameters

Name Type Description
name string

File path

Returns

Promise.<string> — File contents

Throws

  • PathError — If the path is invalid, the file does not exist, or it is a directory

Example

const text = await fs.readTextFile("/hello.txt");
console.log(text);

readDir

readDir(name)

Lists the entries of a directory.

Returns an async iterable of DirEntry objects. Use for await to walk it.

Parameters

Name Type Description
name string

Directory path

Returns

AsyncIterable.<DirEntry> — Directory entries

Throws

  • PathError — If the path is invalid

Example

for await (const entry of fs.readDir("/mydir")) {
  console.log(entry.name, entry.isDir ? "(dir)" : "(file)");
}

writeFile

writeFile(name, data)

Writes data to a file (creates or overwrites).

Accepts a Uint8Array (written in one call) or a ReadableStream of bytes (streamed chunk by chunk). To write a Blob or File, pass its stream: fs.writeFile("/x", blob.stream()). Use writeTextFile for strings.

Parameters

Name Type Description
name string

File path

data Uint8Array | ReadableStream.<Uint8Array>

Bytes to write

Returns

Promise.<void>

Throws

  • PathError — If the path is invalid or the write fails

Example

await fs.writeFile("/hello.txt", new TextEncoder().encode("Hello"));
await fs.writeFile("/data.bin", new Uint8Array([1, 2, 3]));

writeTextFile

writeTextFile(name, text)

Writes a UTF-8 string to a file (creates or overwrites).

Parameters

Name Type Description
name string

File path

text string

Text to write

Returns

Promise.<void>

Throws

  • PathError — If the path is invalid or the write fails

Example

await fs.writeTextFile("/hello.txt", "Hello, World!");

mkdir

mkdir(name, [options], [options.recursive])

Creates a directory.

Parameters

Name Type Description
name string

Directory path

options Object

Options object

options.recursive boolean

Create parent directories

Returns

Promise.<void>

Throws

  • PathError — If the path is invalid, already exists, or the parent is missing

Example

await fs.mkdir("/newdir");
await fs.mkdir("/parent/child", { recursive: true });

remove

remove(name)

Removes a file or empty directory.

Parameters

Name Type Description
name string

Path to remove

Returns

Promise.<void>

Throws

  • PathError — If the path is invalid, does not exist, or the directory is not empty

Example

await fs.remove("/oldfile.txt");

rename

rename(oldPath, newPath)

Renames (or moves) a file or directory.

Renaming a directory rewrites the paths of all descendants so the subtree stays consistent.

Parameters

Name Type Description
oldPath string

Current path of the file or directory

newPath string

New path for the file or directory

Returns

Promise.<void>

Throws

  • PathError — If a path is invalid, the source does not exist, or the target already exists

Example

await fs.rename("/old.txt", "/new.txt");
await fs.rename("/a/file.js", "/b/file.js");

glob

glob(pattern)

Finds files matching a glob pattern.

Parameters

Name Type Description
pattern string

Glob pattern (e.g. "*.txt", "files/**")

Returns

Promise.<Array.<string>> — Matching paths

Example

const files = await fs.glob("*.txt");
const allFiles = await fs.glob("files/**");

Types

FsError

Extends Error.

Error thrown by file system operations.

Thrown errors carry a code property suitable for comparison with ErrorCodes.

PathError

Extends FsError.

Error that includes the path and operation that caused the error.

Thrown errors carry op (the failed operation, e.g. "open" or "read") and path (the path that caused the error).

FileInfo

Information about a file, returned by stat and DirEntry.info.

Properties

Name Type Description
name string

File name.

size bigint

File size in bytes.

modTime Date

Last modification time.

isDir boolean

True if this is a directory.

sys *

System-dependent data (usually null).

DirEntry

An entry in a directory listing, yielded by readDir.

Properties

Name Type Description
name string

Entry name.

isDir boolean

Whether the entry is a directory.

Methods

DirEntry.info

info()

Returns a FileInfo for this entry.

Promise.<FileInfo>

FsFile

An open file handle for reading, writing, and seeking.

Obtain one with open. The handle exposes positional I/O, async iteration, and web streams through FsFile.readable and FsFile.writable.

Properties

Name Type Description
readable ReadableStream.<Uint8Array>

A ReadableStream of the remaining file bytes.

The stream reads in chunks. Reading it to completion, or cancelling it, closes the file handle, so do not close it yourself while the stream is still in use.

writable WritableStream.<Uint8Array>

A WritableStream that writes bytes at the current position.

Closing or aborting the stream closes the file handle, so do not close it yourself while the stream is still in use.

Methods

FsFile.stat

stat()

Retrieves file metadata.

Promise.<FileInfo> — File information

  • PathError — If the file is closed or the operation fails

FsFile.read

read(buf)

Reads data into the buffer and advances the file position.

Name Type Description
buf Uint8Array

Buffer to read data into

Promise.<number> — Number of bytes read (0 on EOF)

  • PathError — If the file is closed or the read fails
const file = await fs.open("/data.bin");
const buf = new Uint8Array(1024);
while (true) {
  const n = await file.read(buf);
  if (n === 0) break;
  console.log("Read chunk:", buf.slice(0, n));
}
await file.close();

FsFile.readAt

readAt(buf, offset)

Reads data at a specific offset without changing the file position.

Name Type Description
buf Uint8Array

Buffer to read data into

offset number

Byte offset to read from

Promise.<number> — Number of bytes read

  • PathError — If the file is closed or the read fails

FsFile.write

write(data)

Writes data at the current position and advances it.

Name Type Description
data Uint8Array | ArrayBuffer | Array.<number>

Data to write

Promise.<number> — Number of bytes written

  • PathError — If the file is closed or the write fails
const file = await fs.open("/output.txt");
const encoder = new TextEncoder();
await file.write(encoder.encode("Hello, "));
await file.write(encoder.encode("World!"));
await file.close();

FsFile.writeAt

writeAt(data, offset)

Writes data at a specific offset without changing the file position.

Name Type Description
data Uint8Array | ArrayBuffer | Array.<number>

Data to write

offset number

Byte offset to write at

Promise.<number> — Number of bytes written

  • PathError — If the file is closed or the write fails

FsFile.close

close()

Closes the file handle.

Promise.<void>

  • PathError — If the file is already closed
const file = await fs.open("/data.txt");
try {
  // ... use file ...
} finally {
  await file.close();
}

FsFile.tell

tell()

Returns the current file position (synchronous, no I/O).

bigint — Current byte offset from the start

  • PathError — If the file is closed

FsFile.seek

seek(offset, [whence])

Changes the file position.

Name Type Description
offset number

Byte offset (negative for SeekMode.End)

whence number

Reference point:

  • SeekMode.Start (0): from the beginning
  • SeekMode.Current (1): from the current position
  • SeekMode.End (2): from the end

Promise.<bigint> — The new position

  • PathError — If the file is closed or the seek fails
const file = await fs.open("/data.txt");
await file.seek(100, fs.SeekMode.Start);
await file.seek(50, fs.SeekMode.Current);
await file.seek(-10, fs.SeekMode.End);
await file.close();

FsFile.Symbol.asyncIterator

Symbol.asyncIterator()

Async iterator over the remaining file bytes, in chunks.

  • PathError — If the file is closed
const file = await fs.open("/large.txt");
for await (const chunk of file) {
  console.log("Chunk:", chunk);
}
await file.close();