Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท fs and fs/promises

Node.js FileHandle class

Reference for the Node.js FileHandle class from fs/promises: read, write, stat, truncate, sync, readLines and streams, plus closing it safely with await using.

A FileHandle is the object you get from fsPromises.open(). It wraps an open file descriptor and gives you promise-returning methods that act on that one file: read(), write(), readFile(), stat(), truncate(), sync() and more. Because the file stays open between calls, you can read in pieces or write at chosen positions without paying the cost of opening the path again.

A handle must be closed. If you forget, the descriptor leaks until garbage collection, and Node prints a warning. Close it in a finally block, or let await using do it for you.

NODE
import fs from "node:fs/promises";

const handle = await fs.open("notes.txt", "r");
try {
  const { size } = await handle.stat();
  console.log(size);
} finally {
  await handle.close();
}

Try it

Node.js Reading and writing at positions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Lines, automatic closing and use after close

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
const handle = await fsPromises.open(path[, flags[, mode]]);
Member Description
handle.fd The numeric file descriptor, or -1 once closed.
handle.read(buffer, offset, length, position) Reads into a buffer. Resolves { bytesRead, buffer }. Also accepts read(buffer, { offset, length, position }) and read({ buffer, ... }).
handle.write(data, position?) Writes a string or buffer. Resolves { bytesWritten, buffer }.
handle.readFile(options?) Reads from the current position to the end. Returns a Buffer or a string.
handle.writeFile(data, options?) / handle.appendFile(data) Writes or appends the whole value.
handle.readv() / handle.writev() Vectored read and write over several buffers.
handle.stat() Resolves an fs.Stats.
handle.truncate(len) Resizes the file.
handle.sync() / handle.datasync() Flushes to storage.
handle.chmod() / handle.chown() / handle.utimes() Changes mode, owner or times.
handle.readLines(options?) Returns a readline interface that is async-iterable by line.
handle.createReadStream() / handle.createWriteStream() Node streams over the handle.
handle.readableWebStream() A web ReadableStream of the contents.
handle.close() Resolves when the descriptor is closed.
handle[Symbol.asyncDispose]() Same as close(); enables await using.

Event: "close", emitted once when the handle is closed.

Errors: EBADF for any method called after close, EISDIR for reading a directory, ENOSPC for a full disk, plus the usual EACCES and EPERM.

Usage notes

  • Close exactly once, and only after every pending operation on the handle has finished. Overlapping calls on one handle are allowed but not ordered, and Node warns against doing that for writes.
  • write(data) without a position writes at the current file offset and advances it. With a position it writes there and does not move the offset. Handles opened with a always append.
  • readFile() starts at the current offset, not always at zero. After a read() it returns only what is left.
  • bytesWritten counts bytes, not characters. A string with non-ASCII characters reports more bytes than its length.
  • await using (explicit resource management) closes the handle even when an exception is thrown. It is the least error-prone pattern when you can use it.
  • Streams over a handle take ownership. Closing the stream closes the handle by default; pass autoClose: false to keep it.
  • Do not pass a raw handle.fd around and then close the handle: the number can be reused by the next opened file, so a stale copy may point at something else.
  • For simple jobs such as reading or writing a whole file, fsPromises.readFile() and fsPromises.writeFile() are shorter and close the file for you.