File handling in Node.js is an essential part of backend development, enabling applications to read, write, update, and delete files efficiently. Node.js provides built-in modules such as fs
(File System) to handle file operations, supporting both synchronous and asynchronous methods.
Synchronous vs. Asynchronous File Handling
Node.js allows developers to perform file operations in two ways:
Synchronous (Blocking) File Handling: These operations block the execution of code until the task is completed.
Asynchronous (Non-Blocking) File Handling: These operations allow other parts of the program to execute while the file operation is being processed.
Blocking vs. Non-Blocking Code
Blocking Code: Executes sequentially, waiting for each task to complete before moving to the next.
Non-Blocking Code: Uses callbacks or promises to continue execution without waiting for the previous task.
Common File Handling Operations
1. Reading a File
Synchronous Read (Blocking)
const fs = require('fs');
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
Asynchronous Read (Non-Blocking)
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
2. Writing to a File
Synchronous Write
fs.writeFileSync('example.txt', 'Hello, Node.js!');
console.log('File written successfully.');
Asynchronous Write
fs.writeFile('example.txt', 'Hello, Node.js!', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File written successfully.');
});
3. Appending Data to a File
Synchronous Append
fs.appendFileSync('example.txt', '\nAppending this text.');
console.log('Data appended successfully.');
Asynchronous Append
fs.appendFile('example.txt', '\nAppending this text.', (err) => {
if (err) {
console.error(err);
return;
}
console.log('Data appended successfully.');
});
4. Deleting a File
Synchronous Delete
fs.unlinkSync('example.txt');
console.log('File deleted successfully.');
Asynchronous Delete
fs.unlink('example.txt', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File deleted successfully.');
});
Ending
File handling in Node.js is straightforward, but it's important to choose the right approach depending on the application requirements. For smaller scripts or CLI tools, synchronous methods might be acceptable, but for web servers and APIs, asynchronous methods are preferred to avoid blocking the event loop. Additionally, using Promises or async/await can improve code readability and maintainability.
If you're working on a high-performance application, consider using streams for large file operations to improve efficiency and reduce memory usage.