File System
Three flavours of the fs module
Section titled “Three flavours of the fs module”Node ships the same filesystem operations in three distinct APIs:
| Style | Import | When to use |
|---|---|---|
| Callback (async) | import fs from 'node:fs' | Legacy code, Node streams |
| Synchronous | import fs from 'node:fs' | CLI scripts, startup-time config |
| Promise (async) | import fs from 'node:fs/promises' | All new server code |
Reading a file
Section titled “Reading a file”Callback style
Section titled “Callback style”import fs from 'node:fs';
fs.readFile('./hello.txt', 'utf8', function(err, data) { if (err) throw err; console.log(data);});Promise style (recommended)
Section titled “Promise style (recommended)”Needs the Node.js runtime — open in StackBlitz to run.
Writing a file
Section titled “Writing a file”writeFile creates the file if it does not exist and replaces the contents if it does. Use appendFile to add to an existing file.
Needs the Node.js runtime — open in StackBlitz to run.
Checking existence and stats
Section titled “Checking existence and stats”Needs the Node.js runtime — open in StackBlitz to run.
Synchronous reads — startup only
Section titled “Synchronous reads — startup only”import { readFileSync } from 'node:fs';
// Acceptable at startup — process has not yet started accepting requestsconst config = JSON.parse(readFileSync('./config.json', 'utf8'));Never call readFileSync inside a request handler, route callback, or any function invoked after the server starts.