The node:fs and node:fs/promises modules provide comprehensive file system APIs for reading, writing, updating, appending, deleting, and streaming files on local or cloud server storage.
flowchart TD
A["fs.readFile() call"] --> B["Libuv Thread Pool Task Queue"]
B --> C["OS File Descriptor Read"]
C --> D["Return Promise / Buffer Data"]
D --> E["Async Handler resuming execution"]
Using the modern node:fs/promises Promise API with async/await:
import fs from 'node:fs/promises';
import path from 'node:path';
const LOG_DIR = path.join(process.cwd(), 'storage', 'logs');
const LOG_FILE = path.join(LOG_DIR, 'app.log');
async function executeLogOperations() {
try {
// 1. Ensure directory exists asynchronously
await fs.mkdir(LOG_DIR, { recursive: true });
// 2. Write file asynchronously
const initialContent = `[INFO] ${new Date().toISOString()} Log file initialized.
`;
await fs.writeFile(LOG_FILE, initialContent, { encoding: 'utf-8' });
// 3. Append to file
const updateContent = `[INFO] ${new Date().toISOString()} User authentication event logged.
`;
await fs.appendFile(LOG_FILE, updateContent, { encoding: 'utf-8' });
// 4. Read file content
const fileData = await fs.readFile(LOG_FILE, 'utf-8');
console.log('--- Current Log File Contents ---');
console.log(fileData);
// 5. Inspect metadata (file stats)
const stats = await fs.stat(LOG_FILE);
console.log(`File Size: ${stats.size} bytes | Created: ${stats.birthtime}`);
} catch (error) {
console.error('File System Error:', error.message);
}
}
executeLogOperations();
node:fs/promises: Avoid synchronous calls like fs.readFileSync() inside web server route handlers because they freeze the main event loop thread.{ recursive: true }: When creating nested directory trees via fs.mkdir(), pass { recursive: true } to prevent errors if parent directories exist.fs.createReadStream() instead of fs.readFile() to prevent high memory usage.Write an async function that checks if a file config.json exists using fs.access(), and if present, reads and parses its JSON content.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With