The Node.js File System module, commonly accessed via require('fs')
, provides an extensive API for interacting with the file system. It allows you to read, write, update, delete, and manage files and directories. Here are some key aspects:
Asynchronous vs Synchronous Methods
1️⃣ Asynchronous Methods
Most methods in the fs
module are asynchronous, meaning they perform I/O operations without blocking the event loop. They typically use an error-first callback pattern.
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});
2️⃣ Synchronous Methods
Synchronous versions (e.g., fs.readFileSync
) block the event loop until the operation completes. These are generally used during startup or in scripts where blocking behavior is acceptable.
const fs = require('fs');
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log('File content:', data);
} catch (err) {
console.error('Error reading file:', err);
}
Common File Operations
- Reading Files:
- Asynchronously:
fs.readFile(path, [options], callback)
- synchronously:
fs.readFileSync(path, [options])
- Asynchronously:
- Writing Files:
- Asynchronously:
fs.writeFile(path, data, [options], callback)
- Synchronously:
fs.writeFileSync(path, data, [options])
- Asynchronously:
- Appending to Files:
- Asynchronously:
fs.appendFile(path, data, [options], callback)
- Synchronously:
fs.appendFileSync(path, data, [options])
- Asynchronously:
- Watching Files:
Use fs.watch() to monitor changes to files or directories.
fs.watch('example.txt', (eventType, filename) => { console.log(`File ${filename} changed: ${eventType}`); });
- Working with Directories:
- Read Contents:
fs.readdir(path, callback)
- Create a directory:
fs.mkdir(path, [options], callback)
- Remove a directory:
fs.rmdir(path, [options], callback)
- Read Contents: