Node.js — File System
Import fs Module
const fs = require('fs');
const fsPromises = require('fs').promises;
Reading Files
// Synchronous
const data = fs.readFileSync('file.txt', 'utf8');
console.log(data);
// Asynchronous
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Promise-based
const data = await fsPromises.readFile('file.txt', 'utf8');
Writing Files
// Synchronous
fs.writeFileSync('output.txt', 'Hello, World!');
// Asynchronous
fs.writeFile('output.txt', 'Hello', (err) => {
if (err) throw err;
console.log('File written');
});
// Promise-based
await fsPromises.writeFile('output.txt', 'Hello');
Append to Files
fs.appendFileSync('log.txt', 'New line\n');
await fsPromises.appendFile('log.txt', 'New line\n');
File Operations
// Check if file exists
if (fs.existsSync('file.txt')) { ... }
// Delete file
fs.unlinkSync('file.txt');
// Rename file
fs.renameSync('old.txt', 'new.txt');
// Get file stats
const stats = fs.statSync('file.txt');
console.log(stats.size, stats.mtime);
Directory Operations
// Create directory
fs.mkdirSync('new-dir', { recursive: true });
// Read directory
const files = fs.readdirSync('.');
// Remove directory
fs.rmdirSync('dir');
Mini Practice
- Read a file
- Write to a file
- Append content
- List directory contents
Up Next
Continue with Path — working with file paths.
Related Topics
Frequently Asked Questions about File System
What is File System in Node.js?
File System is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn File System?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn File System.
Why is File System important in Node.js?
File System is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.