Why Use the File System Module?
Node.js applications often need to interact with files for tasks like:
- Storing data.
- Reading configuration files.
- Logging application activity.
- Serving files dynamically (e.g., images or documents).
The fs
module makes these tasks easy and efficient with its built-in methods.
Importing the File System Module
To use the fs module, you need to import it in your script:
const fs = require('fs');
The fs module provides both synchronous and asynchronous methods:
- Synchronous Methods: These block the execution of code until the file operation completes.
- Asynchronous Methods: These do not block the code execution and use callbacks or promises for handling results.
File System Operations
1. Reading a File
You can read the contents of a file using the fs.readFile method.
Example: Asynchronous File Reading
const fs = require('fs');
// Read file asynchronously
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err);
return;
}
console.log('File content:', data);
});
Explanation:
- The first argument is the file name (example.txt).
- The second argument is the encoding (utf8).
- The third argument is a callback function that handles the result or error.
Output:
If the file example.txt contains Hello, Node.js!, the output will be:
File content: Hello, Node.js!
2. Writing to a File
You can write data to a file using the fs.writeFile method. If the file does not exist, it will be created automatically.
Example: Writing to a File
const fs = require('fs');
// Write data to a file
fs.writeFile('example.txt', 'This is Node.js!', (err) => {
if (err) {
console.error('Error writing to the file:', err);
return;
}
console.log('File written successfully!');
});
Output:
This creates a file named example.txt with the content:
This is Node.js!
3. Appending Data to a File
If you want to add data to an existing file without overwriting its content, use fs.appendFile.
Example: Appending Data
fs.appendFile('example.txt', '\nAppended text.', (err) => {
if (err) {
console.error('Error appending to the file:', err);
return;
}
console.log('Data appended successfully!');
});
Output:
The file example.txt will now contain:
This is Node.js!
Appended text.
4. Deleting a File
To delete a file, use the fs.unlink method.
Example: Deleting a File
fs.unlink('example.txt', (err) => {
if (err) {
console.error('Error deleting the file:', err);
return;
}
console.log('File deleted successfully!');
});
5. Creating a Directory
You can create a new directory using the fs.mkdir method.
Example: Creating a Directory
fs.mkdir('newFolder', (err) => {
if (err) {
console.error('Error creating the directory:', err);
return;
}
console.log('Directory created successfully!');
});
6. Deleting a Directory
To remove a directory, use the fs.rmdir method.
Example: Removing a Directory
fs.rmdir('newFolder', (err) => {
if (err) {
console.error('Error removing the directory:', err);
return;
}
console.log('Directory removed successfully!');
});
7. Checking if a File or Directory Exists
You can check whether a file or directory exists using the fs.existsSync method.
Example: Checking Existence
if (fs.existsSync('example.txt')) {
console.log('The file exists!');
} else {
console.log('The file does not exist.');
}
Synchronous vs Asynchronous Methods
Node.js provides both synchronous and asynchronous versions of most file system operations.
Synchronous Example:
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
Note: Synchronous methods block the event loop, which may impact performance in large applications. Always prefer asynchronous methods unless necessary.
Real-World Use Case
Imagine you’re building a logging system for a web application. The fs module can help you write log files:
Example: Logging with Timestamps
const fs = require('fs');
// Log a message with a timestamp
const logMessage = `Log entry at ${new Date().toISOString()}: User logged in.\n`;
fs.appendFile('log.txt', logMessage, (err) => {
if (err) {
console.error('Error writing to log file:', err);
return;
}
console.log('Log entry added successfully!');
});
Output in log.txt:
Log entry at 2025-01-22T10:00:00.000Z: User logged in.