fs.readFileSync()
Synchronously reads the entire contents of a file, blocking the event loop.
Syntax
fs.readFileSync(path[, options]) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
path | string | Buffer | URL | integer | Yes | The filename or file descriptor. |
options | object | string | No | Encoding string or object with `encoding` and `flag`. |
Returns
string | Buffer — The file contents (string when an encoding is given).
Examples
import { readFileSync } from 'node:fs';
const pkg = JSON.parse(readFileSync('./package.json', 'utf8'));
console.log(pkg.name);
Output
my-app
import { readFileSync } from 'node:fs';
const key = readFileSync('./private.pem');
console.log(key.length, 'bytes');
Output
1704 bytes
Notes
Blocks the entire event loop until the read finishes, so use it only
for startup config or CLI scripts, never inside request handlers.
Throws synchronously on error; wrap in try/catch.