File System Operations
The node:fs and node:fs/promises modules provide APIs for reading, writing, updating, deleting, and inspecting files and directories. Prefer asynchronous APIs in server applications when the operation may involve significant I/O.
Synchronous file operations block the JavaScript execution thread and should generally be reserved for startup tasks or scripts where blocking is acceptable.
Reading a File Asynchronously
import { readFile } from 'node:fs/promises';
const data = await readFile('config.json', 'utf8');
console.log(data);💡 The Promise-based file system API allows the application to read a file without using a callback.
Key Takeaways
- Prefer asynchronous file APIs in request-handling code.
- Use
node:fs/promisesfor Promise-based file operations. - Avoid blocking file operations inside high-throughput request handlers.
Knowledge Check
Why should synchronous file operations usually be avoided inside HTTP handlers?