Read application assets
Load a small configuration or template file during asynchronous application startup.
Node.js · Function
fs.readFile() asynchronously reads an entire file into memory and reports completion through a callback. It returns text when an encoding is supplied; otherwise it returns a Buffer.
The callback-based fs.readFile() asynchronously reads the complete contents of a path into memory. Pass an encoding through options to receive a string; otherwise the result is a Buffer, and completion reports either an error or the data.
fs.readFile(path[, options], callback)| Name | Type | Description |
|---|---|---|
path | string | Buffer | URL | integer | The file path or a readable file descriptor. |
options | string | Object | Optional encoding or options object, including encoding and file flags. |
callback | function | Called after the operation completes with an error or the file data. |
The callback receives the file contents as a string when encoding is specified, otherwise as a Buffer; errors are passed as the first callback argument.
import { readFile } from 'node:fs/promises';
const text = await readFile(new URL('./config.json', import.meta.url), 'utf8');
console.log(text);Reads config.json asynchronously as UTF-8 text and prints its contents.
Load a small configuration or template file during asynchronous application startup.
Retrieve a complete text or binary file when incremental processing is unnecessary.
Read user-provided files after validating the path and handling filesystem errors.
fs.readFile(path[, options], callback) performs an asynchronous full-file read. The callback receives an error and the resulting string or Buffer.
Follow-up: How would you handle a very large file? Use fs.createReadStream() so data can be processed incrementally instead of being fully buffered.
Without an encoding, the returned data is a Buffer. Supplying an encoding, such as 'utf8', makes the result a string.
Follow-up: What happens when options is a string? It is treated as the encoding value.
The method yields control between chunks while reading, so it does not synchronously block JavaScript execution. It still stores the entire file in memory before completion.
Follow-up: When is fs.readFileSync() preferable? Only when synchronous behavior is intentionally required, since it blocks the event loop.
fs.readFileSyncfsPromises.readFilefs.createReadStreamfs.open