fs.readFile()
Asynchronously reads the entire contents of a file.
Syntax
await readFile(path[, options]) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
path | string | Buffer | URL | integer | Yes | The filename or file descriptor to read. |
options | object | string | No | An encoding string (e.g. `'utf8'`) or an object with `encoding`, `flag`, and `signal` (an AbortSignal) properties. With no encoding a Buffer is returned. |
Returns
Promise<string | Buffer> — Resolves with the file contents.
Examples
import { readFile } from 'node:fs/promises';
const text = await readFile('./config.json', 'utf8');
console.log(JSON.parse(text).port);
Output
3000
import { readFile } from 'node:fs/promises';
const buf = await readFile('./logo.png');
console.log(buf.length, 'bytes');
Output
20480 bytes
Notes
Reads the whole file into memory; for large files use
`createReadStream`. Always pass an encoding when you want a string,
otherwise you get a Buffer. The callback API (`fs.readFile`) is the
older form; prefer the promises API shown here.