Incremental file processing
Process large files without loading their complete contents into memory.
Node.js · Function
Creates a readable stream for a file, allowing data to be consumed incrementally. Options can select encoding, byte ranges, buffering, and file-descriptor behavior.
createReadStream() constructs a readable file stream rather than loading the whole file at once. The path identifies the file unless an existing file descriptor is supplied; options control flags, encoding, descriptor ownership, permissions, byte bounds, and buffering.
fs.createReadStream(path[, options])| Name | Type | Description |
|---|---|---|
path | string | Buffer | URL | integer | File path, URL, or file descriptor source used to open the stream. |
options | string | Object | Optional configuration including flags, encoding, fd, mode, autoClose, start, end, and highWaterMark. |
A new fs.ReadStream object.
import { createReadStream } from 'node:fs';
const stream = createReadStream('package.json', { encoding: 'utf8' });
for await (const chunk of stream) {
process.stdout.write(chunk);
}Reads package.json incrementally as UTF-8 text and writes each chunk to standard output.
Process large files without loading their complete contents into memory.
Serve downloads or other response bodies while data arrives in chunks.
Inspect or transform only a selected region of a file.
It returns a ReadStream that exposes file data through Node.js readable-stream behavior. Data can be consumed incrementally, avoiding the need to buffer the entire file in memory.
Follow-up: How would you read only a byte interval? Pass start and end in the options object; the endpoints are inclusive and zero-based.
The path identifies the file, while options can configure flags, encoding, an existing file descriptor, mode, automatic closure, byte range, and highWaterMark. If fd is supplied, the stream uses that descriptor instead of opening path.
Follow-up: What happens to the open event with an existing descriptor? The documentation states that no open event is emitted when fd is specified.
The default range reads the file as a stream, and start/end restrict reading to an inclusive byte range. With an existing fd and no start, reading proceeds from the descriptor's current position.
Follow-up: What should be considered when setting autoClose to false? The caller must arrange descriptor cleanup, including after errors.
fs.ReadStreamfs.createWriteStreamfs.openstream.Readable