Node.js Masterclass
High-Performance Backends01.Home02.Introduction03.Environment Setup04.Modules & Exports05.File System (fs)06.Path & OS Modules07.Buffer & Streams08.Events & EventEmitter09.HTTP Module10.NPM & Package.json11.Express.js Fundamentals12.Express Routing13.Express Middleware14.RESTful API Development15.Asynchronous Programming16.Error Handling17.Database with Mongoose18.Authentication with JWT19.Environment Variables20.Testing with Jest21.Deployment & PM2
File System (fs) Module
The fs module allows you to work with the file system on your computer. You can read, write, create, update, and delete files.
1. Importing the fs Module
const fs = require('fs');
// Or using promises (recommended)
const fsPromises = require('fs/promises');2. Reading Files
You can read files synchronously (blocking) or asynchronously (non-blocking).Always prefer asynchronous methods in production to keep the application responsive.
// Asynchronous way (using callback)
fs.readFile('hello.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Using Promises (Modern)
async function readFile() {
try {
const data = await fsPromises.readFile('hello.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}3. Writing Files
The writeFile method replaces the content if the file exists, or creates a new file if it doesn't.
const content = 'Learning Node.js is fun!';
fs.writeFile('notes.txt', content, (err) => {
if (err) throw err;
console.log('File written successfully!');
});4. Appending to Files
If you want to add content to an existing file instead of replacing it, use appendFile.
fs.appendFile('notes.txt', '\nNew line added!', (err) => {
if (err) throw err;
console.log('Content appended!');
});5. Deleting Files
fs.unlink('temp.txt', (err) => {
if (err) throw err;
console.log('File deleted!');
});Best Practice: Always handle errors in file operations. A missing file or bad permissions can crash your application if not caught properly.