File System (fs) Module
The built-in fs (File System) module provides APIs for reading, writing, updating, and deleting files and directories. It offers both synchronous and asynchronous variants of every operation.
1 Sync vs Async File Operations
Node.js strongly prefers asynchronous file operations to avoid blocking the event loop:
- Synchronous (Sync): Blocks execution until the operation completes. Only suitable for startup scripts or CLI tools.
- Asynchronous (Callback): Non-blocking. Passes the result to a callback function when ready.
- Promise-based (fs/promises): Modern async/await style, cleanest approach for new code.
2 Reading & Writing Files
JavaScript — fs/promises
const fs = require('fs/promises');
const path = require('path');
async function fileOperations() {
const filePath = path.join(__dirname, 'data.txt');
// Write a file (creates if not exists, overwrites if exists)
await fs.writeFile(filePath, 'Hello from Node.js!
Line 2 of data.', 'utf8');
console.log('File written successfully.');
// Read the file back
const content = await fs.readFile(filePath, 'utf8');
console.log('File content:
', content);
// Append to an existing file
await fs.appendFile(filePath, '
Appended line.');
// Get file metadata
const stats = await fs.stat(filePath);
console.log('File size:', stats.size, 'bytes');
console.log('Modified:', stats.mtime);
// Delete the file
await fs.unlink(filePath);
console.log('File deleted.');
}
fileOperations().catch(console.error);
3 Working with Directories
JavaScript — Directory Operations
const fs = require('fs/promises');
async function dirOps() {
// Create directory (recursive creates parent dirs too)
await fs.mkdir('./output/reports', { recursive: true });
// List directory contents
const entries = await fs.readdir('./output', { withFileTypes: true });
entries.forEach(entry => {
console.log(entry.name, entry.isDirectory() ? '[DIR]' : '[FILE]');
});
// Remove empty directory
await fs.rmdir('./output/reports');
}
dirOps();
4 Code Challenge
Challenge: Write a script that reads all
.txt files from a directory, concatenates their contents, and writes the result to a single merged.txt output file.