Reading & Writing Files
The fs module reads and writes files, synchronously or asynchronously.
Syntax
fs.readFile(path, encoding, callback)The built-in fs (file system) module lets your program read and write files on disk. Most functions come in two flavors:
- Asynchronous — takes a callback, does not block. Preferred.
- Synchronous — ends in
Sync, blocks until finished. Simpler for scripts.
Blocking vs non-blocking
Synchronous calls pause the whole program until the disk responds. In a server that handles many users, prefer the asynchronous or promise-based versions so the app stays responsive.
Example
const fs = require('fs');
// Asynchronous (non-blocking) read
fs.readFile('note.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log('File contents:', data);
});
// Synchronous (blocking) write
fs.writeFileSync('out.txt', 'Saved by Node!');
console.log('File written.');When to use it
- A log-rotation script reads existing log files with `fs.readFile` and writes rotated archives using `fs.writeFile` nightly.
- An e-commerce site generates PDF invoices by writing binary data to disk with `fs.writeFile` after payment confirmation.
- A static site generator reads Markdown source files with `fs.readFile` and writes compiled HTML files to a dist folder.
More examples
Read a file asynchronously
Reads a text file asynchronously with a callback -- Node.js's classic I/O pattern.
const fs = require('fs');
fs.readFile('notes.txt', 'utf8', (err, data) => {
if (err) { console.error(err); return; }
console.log(data);
});Write a file asynchronously
Creates or overwrites `output.txt` with the provided string content.
const fs = require('fs');
fs.writeFile('output.txt', 'Hello, file system!', 'utf8', (err) => {
if (err) throw err;
console.log('File written successfully');
});Append to an existing file
Uses `fs.appendFile` to add a timestamped log line without overwriting existing content.
const fs = require('fs');
const line = `[${new Date().toISOString()}] Server started\n`;
fs.appendFile('app.log', line, (err) => {
if (err) throw err;
});
Discussion