Startup configuration
Load a small configuration or metadata file during application startup.
Node.js · Function
readFileSync() synchronously reads an entire file and returns its contents. It yields a Buffer by default or a string when an encoding is selected.
readFileSync() reads the complete contents of a file before returning. The path may be a string, Buffer, URL, or file descriptor; options can select an encoding, in which case a string is returned, otherwise the result is a Buffer. Because it is synchronous, execution waits until reading finishes or an error is thrown.
fs.readFileSync(path[, options])| Name | Type | Description |
|---|---|---|
path | string | Buffer | URL | integer | File path, file descriptor, or URL identifying the file to read. |
options | Object | string | Optional encoding and file-system read settings; an encoding causes a string result. |
encoding | BufferEncoding | Encoding name, such as 'utf8', when options is supplied as a string. |
The complete file contents as a Buffer, or as a string when an encoding is specified.
import { readFileSync } from 'node:fs';
const text = readFileSync(new URL('./config.json', import.meta.url), 'utf8');
const config = JSON.parse(text);
console.log(config);Reads a nearby JSON file synchronously as UTF-8 text and parses it.
Load a small configuration or metadata file during application startup.
Read a fixture or snapshot in a short command-line script or test.
Load a module-relative asset from an ES module using a URL.
It synchronously reads the entire file and returns its contents. With an encoding such as 'utf8', it returns a string; without one, it returns a Buffer.
Follow-up: When would you avoid it? Avoid it on an event-loop path that handles concurrent requests; use an asynchronous API or a stream instead.
The path can identify the file directly, and the options argument can specify an encoding or other file-reading settings. A supplied encoding changes the returned value from a Buffer to a string.
Follow-up: How can an ES module read a file relative to itself? Pass a URL constructed with new URL('./file', import.meta.url).
It is the synchronous counterpart of fs.readFile(). It completes before the next statement runs and reports failures by throwing an exception.
Follow-up: What is a better approach for a large file or client request? Prefer a stream or partitioned asynchronous reads to avoid blocking and long single operations.
fs.readFilefs.readfs.createReadStreamfs.promises.readFile