READING MODULES
In Node.js, reading files from the file system is handled through the built-in fs
(File System) module. This module enables interaction with the local disk, such as reading, writing, or modifying files and directories. It supports both synchronous and asynchronous operations.
Reading Files: Two Main Methods–
- Asynchronous – Preferred for non-blocking I/O, especially in production environments.
- Method:
fs.readFile(path, [options], callback)
- Use Case: Doesn’t halt execution; suitable for high-performance applications.
- Method:
- Synchronous – Blocks execution until the file is read.
- Method:
fs.readFileSync(path, [options])
- Use Case: Simpler for quick scripts or when blocking is acceptable.
- Method:
EXAMPLE CODE
#Asynchronous File Read
const fs = require(‘fs’);
fs.readFile(‘./example.txt’, ‘utf8’, (err, data) => {
if (err) {
console.error(‘Error reading file:’, err);
return;
}
console.log(‘File contents:’, data);
});
#Synchronous File Read
const fs = require(‘fs’);
try {
const data = fs.readFileSync(‘./example.txt’, ‘utf8’);
console.log(‘File contents:’, data);
} catch (err) {
console.error(‘Error reading file:’, err);
}
WRITING MODULES
Modules in Node.js provide a structured way to organize and reuse code effectively. By segmenting functionality into discrete units, developers can maintain clarity, scalability, and flexibility in application design. Whether working with built-in utilities like fs
or crafting custom solutions, module systems form the foundation of modern Node.js development. Understanding patterns and best practices empowers efficient and maintainable backend architecture.
Writing Files: Two Main Methods
- Asynchronous – Performs writing without blocking the event loop.
- Method:
fs.writeFile(path, data, [options], callback)
- Use Case: Ideal for non-blocking applications or concurrent writes.
- Method:
- Synchronous – Writes data and halts further execution until completion.
- Method:
fs.writeFileSync(path, data, [options])
- Use Case: Suitable for simple tasks or setup scripts where blocking is acceptable.
- Method:
EXAMPLE CODE
#Asynchronous File Write
const fs = require(‘fs’);
const content = ‘This is sample content written asynchronously.’;
fs.writeFile(‘./output.txt’, content, ‘utf8’, (err) => {
if (err) {
console.error(‘Error writing file:’, err);
return;
}
console.log(‘File written successfully.’);
});
#Synchronous File Write
const fs = require(‘fs’);
const content = ‘This is sample content written synchronously.’;
try {
fs.writeFileSync(‘./output.txt’, content, ‘utf8’);
console.log(‘File written successfully.’);
} catch (err) {
console.error(‘Error writing file:’, err);
}
DELETING MODULES
In Node.js, deleting files from the local file system is handled through the built-in fs
module. This module offers both synchronous and asynchronous methods to remove files programmatically. Understanding how to safely perform file deletions is essential for tasks like log cleanup, temporary file management, or handling user uploads. The following approaches illustrate how to implement deletion using Node.js.
Deleting Files: Two Main Methods
- Asynchronous Deletion
- Method:
fs.unlink(path, callback)
- Use Case: Non-blocking, suitable for production environments and concurrent tasks.
- Method:
- Synchronous Deletion
- Method:
fs.unlinkSync(path)
- Use Case: Useful for scripts or scenarios where blocking is acceptable.
- Method:
EXAMPLE CODE
#Asynchronous File Deletion
const fs = require(‘fs’);
fs.unlink(‘./output.txt’, (err) => {
if (err) {
console.error(‘Error deleting file:’, err);
return;
}
console.log(‘File deleted successfully.’);
});
#Synchronous File Deletion
const fs = require(‘fs’);
try {
fs.unlinkSync(‘./output.txt’);
console.log(‘File deleted successfully.’);
} catch (err) {
console.error(‘Error deleting file:’, err);
}
DIFFERENCE BETWEEN SYNCHRONOUS VS ASYNCHRONOUS FILE OPERATIONS
ASPECT | SYNCHRONOUS | ASYNCHRONOUS |
EXECUTION FLOW | Blocks the event loop until operation completes | Non-blocking; continues execution while operation proceeds |
PERFORMANCE | Slower for large-scale or I/O-heavy applications | Faster and more scalable under high load |
METHOD PREFIX | Methods end with Sync (e.g., fs.readFileSync ) | Methods without Sync (e.g., fs.readFile ) |
ERROR HANDLING | Uses try...catch blocks | Uses callbacks or Promises (err argument) |
USE CASE | Suitable for small scripts or startup routines | Recommended for production apps and concurrent workloads |
THREADING IMPACT | Blocks the single-threaded event loop | Offloads I/O to libuv thread pool |
CALLBACK REQUIREMENT | Not required, returns result immediately | Requires callback or async/await for result handling |
USER EXPERIENCE IMPACT | May cause delays or freezing in interactive apps | Keeps UI or server responsive |