fs.createReadStream()
Creates a readable stream for incrementally reading a file.
Syntax
fs.createReadStream(path[, options]) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
path | string | Buffer | URL | Yes | The file to read. |
options | object | string | No | Encoding string, or object with `encoding`, `start`, `end`, `highWaterMark`, and `signal` for ranged or chunked reads. |
Returns
fs.ReadStream — A Readable stream emitting data chunks.
Examples
import { createReadStream } from 'node:fs';
const stream = createReadStream('./big.log', 'utf8');
let lines = 0;
stream.on('data', (chunk) => {
lines += chunk.split('\n').length - 1;
});
stream.on('end', () => console.log(lines, 'lines'));
Output
120000 lines
import { createReadStream } from 'node:fs';
import { createServer } from 'node:http';
createServer((req, res) => {
createReadStream('./video.mp4').pipe(res);
}).listen(3000);
Notes
Streams keep memory flat regardless of file size, unlike `readFile`.
Always handle the `'error'` event or pipe with `pipeline` so a
read failure does not crash the process.