The File System module in Node.js, often referred to as fs, provides an API to interact with the file system, making it possible to read from, write to, and modify files and directories. This functionality is crucial for many applications, from serving static files to reading configuration data or logging.
This guide will delve into the various aspects of the fs module, complete with examples.
1. Including the File System Module
To use the fs module, you first need to import it:
const fs = require('fs');
2. Reading Files
One of the most fundamental operations is reading from a file.
2.1. Synchronous Read:
Using fs.readFileSync(), you can read a file synchronously. It's not advisable for large files or performance-critical applications as it blocks the event loop.
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
2.2. Asynchronous Read:
Using fs.readFile(), you can read a file asynchronously.
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
3. Writing to Files
Similarly, you can write data to files either synchronously or asynchronously.
3.1. Synchronous Write:
const content = 'Hello, Node.js!';
fs.writeFileSync('example.txt', content);
3.2. Asynchronous Write:
fs.writeFile('example.txt', content, (err) => {
if (err) throw err;
console.log('File has been saved!');
});
4. Appending to Files
To append data to an existing file:
const additionalContent = ' Appending this text.';
fs.appendFile('example.txt', additionalContent, (err) => {
if (err) throw err;
console.log('Data was appended to file!');
});
5. Deleting Files
To delete a file:
fs.unlink('example.txt', (err) => {
if (err) throw err;
console.log('File deleted!');
});
6. Directories
The fs module also provides methods to work with directories.
6.1. Creating a Directory:
fs.mkdir('newDirectory', (err) => {
if (err) throw err;
console.log('Directory created!');
});
6.2. Deleting a Directory:
fs.rmdir('newDirectory', (err) => {
if (err) throw err;
console.log('Directory deleted!');
});
6.3. Reading the Contents of a Directory:
fs.readdir('path/to/directory', (err, files) => {
if (err) throw err;
console.log(files);
});
7. Checking File/Directory Stats
To get detailed information about a file or directory:
fs.stat('example.txt', (err, stats) => {
if (err) throw err;
console.log(`File Size: ${stats.size}`);
console.log(`Is File: ${stats.isFile()}`);
console.log(`Is Directory: ${stats.isDirectory()}`);
});
8. File Streams
For large files, it's efficient to use streams. Streams allow you to work with parts of the file without reading or writing the entire file into memory.
8.1. Reading with Streams:
const readStream = fs.createReadStream('largeFile.txt', 'utf8');
readStream.on('data', (chunk) => {
console.log(chunk);
});
8.2. Writing with Streams:
const writeStream = fs.createWriteStream('output.txt');
readStream.pipe(writeStream);
9. Watching for File Changes
The fs.watch() method allows you to watch for changes in a file or directory.
fs.watch('example.txt', (eventType, filename) => {
if (filename) {
console.log(`${filename} - ${eventType}`);
}
});
10. Error Handling
Many of the asynchronous methods in the fs module follow the error-first callback pattern. This means the first argument passed to the callbacks will be an error object if an error occurred.
fs.readFile('nonexistent.txt', 'utf8', (err, data) => {
if (err) {
console.error('There was an error reading the file:', err);
return;
}
console.log(data);
});
11. Promises and Async/Await with fs
With Node.js v10.0.0 and above, fs provides promise-based versions of its functions:
const fsProm
ises = require('fs').promises;
async function readFileAsync() {
try {
const data = await fsPromises.readFile('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error('There was an error:', err);
}
}
readFileAsync();
The fs module in Node.js provides a robust set of tools for interacting with the file system. Whether you're building a small script or a large-scale application, understanding the capabilities of the fs module can be tremendously beneficial. Always remember to consider the implications of synchronous versus asynchronous operations and to handle errors appropriately to ensure the resilience of your applications.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here