Introduction to the fs
Module
The fs
module is built into Node.js and provides both synchronous and asynchronous methods for interacting with the file system. Common operations include:
- Reading and writing files
- Creating and deleting files or directories
- Renaming and moving files
To use the fs
module, import it into your script:
const fs = require('fs');
For promise-based methods, use:
const fsPromises = require('fs').promises;
Reading Files
Asynchronous File Reading
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});
Using Promises
fsPromises.readFile('example.txt', 'utf8')
.then(data => console.log('File content:', data))
.catch(err => console.error('Error reading file:', err));
Writing Files
Asynchronous File Writing
fs.writeFile('example.txt', 'Hello, World!', err => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('File written successfully!');
});
Using Promises
fsPromises.writeFile('example.txt', 'Hello, World!')
.then(() => console.log('File written successfully!'))
.catch(err => console.error('Error writing file:', err));
Appending Data to Files
Adding Data to an Existing File
fs.appendFile('example.txt', '\nAdditional data.', err => {
if (err) {
console.error('Error appending to file:', err);
return;
}
console.log('Data appended successfully!');
});
Deleting Files
Removing a File
fs.unlink('example.txt', err => {
if (err) {
console.error('Error deleting file:', err);
return;
}
console.log('File deleted successfully!');
});
Managing Directories
Creating a Directory
fs.mkdir('new-directory', { recursive: true }, err => {
if (err) {
console.error('Error creating directory:', err);
return;
}
console.log('Directory created successfully!');
});
Removing a Directory
fs.rmdir('new-directory', err => {
if (err) {
console.error('Error removing directory:', err);
return;
}
console.log('Directory removed successfully!');
});
Watching Files and Directories
Use fs.watch
to monitor changes in files or directories:
fs.watch('example.txt', (eventType, filename) => {
if (filename) {
console.log(`${filename} file changed: ${eventType}`);
} else {
console.log('Filename not provided');
}
});
Best Practices
- Prefer Asynchronous Methods: Always use asynchronous methods to avoid blocking the main thread, especially for I/O-intensive tasks.
- Handle Errors Gracefully: Always handle errors to ensure application reliability.
- Leverage Promises or Async/Await: For clean and maintainable code, use promise-based methods or
async/await
syntax. - Utilize the
path
Module: Use thepath
module to handle file paths effectively, particularly in cross-platform applications.
The fs
module is a powerful and versatile tool for managing files and directories in Node.js. By mastering its features and adhering to best practices, you can perform file system operations efficiently and build robust, scalable applications.
About Lavesh Katariya
Innovative Full-Stack Developer | Technical Team Lead | Cloud Solutions Architect
With over a decade of experience in building and leading cutting-edge web application projects, I specialize in developing scalable, high-performance platforms that drive business growth. My expertise spans both front-end and back-end development, making me a versatile and hands-on leader capable of delivering end-to-end solutions.