In this section, we will explore the File System (fs) module in Node.js, which allows you to interact with the file system on your computer. This module provides a variety of methods to read, write, update, delete, and manipulate files and directories.
Key Concepts
-
Synchronous vs Asynchronous Methods:
- Synchronous methods block the execution of code until the operation is complete.
- Asynchronous methods do not block the execution and use callbacks or promises to handle the result.
-
Common Operations:
- Reading files
- Writing files
- Appending to files
- Deleting files
- Working with directories
Importing the File System Module
To use the File System module, you need to import it using the require
function:
Reading Files
Asynchronous Reading
fs.readFile('example.txt', 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } console.log('File content:', data); });
Synchronous Reading
try { const data = fs.readFileSync('example.txt', 'utf8'); console.log('File content:', data); } catch (err) { console.error('Error reading file:', err); }
Writing Files
Asynchronous Writing
const content = 'Hello, World!'; fs.writeFile('example.txt', content, 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('File written successfully'); });
Synchronous Writing
const content = 'Hello, World!'; try { fs.writeFileSync('example.txt', content, 'utf8'); console.log('File written successfully'); } catch (err) { console.error('Error writing file:', err); }
Appending to Files
Asynchronous Appending
const additionalContent = '\nAppended content'; fs.appendFile('example.txt', additionalContent, 'utf8', (err) => { if (err) { console.error('Error appending to file:', err); return; } console.log('Content appended successfully'); });
Synchronous Appending
const additionalContent = '\nAppended content'; try { fs.appendFileSync('example.txt', additionalContent, 'utf8'); console.log('Content appended successfully'); } catch (err) { console.error('Error appending to file:', err); }
Deleting Files
Asynchronous Deletion
fs.unlink('example.txt', (err) => { if (err) { console.error('Error deleting file:', err); return; } console.log('File deleted successfully'); });
Synchronous Deletion
try { fs.unlinkSync('example.txt'); console.log('File deleted successfully'); } catch (err) { console.error('Error deleting file:', err); }
Working with Directories
Creating a Directory
Asynchronous Creation
fs.mkdir('newDir', { recursive: true }, (err) => { if (err) { console.error('Error creating directory:', err); return; } console.log('Directory created successfully'); });
Synchronous Creation
try { fs.mkdirSync('newDir', { recursive: true }); console.log('Directory created successfully'); } catch (err) { console.error('Error creating directory:', err); }
Reading a Directory
Asynchronous Reading
fs.readdir('newDir', (err, files) => { if (err) { console.error('Error reading directory:', err); return; } console.log('Directory contents:', files); });
Synchronous Reading
try { const files = fs.readdirSync('newDir'); console.log('Directory contents:', files); } catch (err) { console.error('Error reading directory:', err); }
Deleting a Directory
Asynchronous Deletion
fs.rmdir('newDir', { recursive: true }, (err) => { if (err) { console.error('Error deleting directory:', err); return; } console.log('Directory deleted successfully'); });
Synchronous Deletion
try { fs.rmdirSync('newDir', { recursive: true }); console.log('Directory deleted successfully'); } catch (err) { console.error('Error deleting directory:', err); }
Practical Exercise
Task
- Create a new directory named
testDir
. - Inside
testDir
, create a file namedtestFile.txt
and write some content to it. - Append additional content to
testFile.txt
. - Read and log the content of
testFile.txt
. - Delete
testFile.txt
. - Delete
testDir
.
Solution
const fs = require('fs'); // Step 1: Create a new directory fs.mkdir('testDir', { recursive: true }, (err) => { if (err) { console.error('Error creating directory:', err); return; } console.log('Directory created successfully'); // Step 2: Create a file and write content fs.writeFile('testDir/testFile.txt', 'Initial content', 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('File written successfully'); // Step 3: Append additional content fs.appendFile('testDir/testFile.txt', '\nAppended content', 'utf8', (err) => { if (err) { console.error('Error appending to file:', err); return; } console.log('Content appended successfully'); // Step 4: Read and log the content fs.readFile('testDir/testFile.txt', 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } console.log('File content:', data); // Step 5: Delete the file fs.unlink('testDir/testFile.txt', (err) => { if (err) { console.error('Error deleting file:', err); return; } console.log('File deleted successfully'); // Step 6: Delete the directory fs.rmdir('testDir', { recursive: true }, (err) => { if (err) { console.error('Error deleting directory:', err); return; } console.log('Directory deleted successfully'); }); }); }); }); }); });
Conclusion
In this section, we covered the basics of the File System module in Node.js, including how to read, write, append, and delete files, as well as how to work with directories. Understanding these operations is crucial for handling file I/O in your Node.js applications. In the next module, we will delve into working with streams, which provide a more efficient way to handle large files and data streams.
Node.js Course
Module 1: Introduction to Node.js
Module 2: Core Concepts
Module 3: File System and I/O
Module 4: HTTP and Web Servers
Module 5: NPM and Package Management
- Introduction to NPM
- Installing and Using Packages
- Creating and Publishing Packages
- Semantic Versioning
Module 6: Express.js Framework
- Introduction to Express.js
- Setting Up an Express Application
- Middleware
- Routing in Express
- Error Handling
Module 7: Databases and ORMs
- Introduction to Databases
- Using MongoDB with Mongoose
- Using SQL Databases with Sequelize
- CRUD Operations
Module 8: Authentication and Authorization
Module 9: Testing and Debugging
- Introduction to Testing
- Unit Testing with Mocha and Chai
- Integration Testing
- Debugging Node.js Applications
Module 10: Advanced Topics
Module 11: Deployment and DevOps
- Environment Variables
- Using PM2 for Process Management
- Deploying to Heroku
- Continuous Integration and Deployment