Ever wanted your Node.js app to read from or write to a file? Or maybe let users upload images and documents?
Thatโs exactly what weโll learn today! ๐ Weโll use simple language, fun code, and real examples โ just like Iโm teaching my younger cousin ๐ก
๐ฆ What Is the File System in Node.js?
Every computer has a file system โ a way to organize and manage files and folders.
Node.js gives us a cool tool to play with files: the fs module (short for File System).
This module lets us:
โ Read files โ Write files โ Update files โ Delete files โ And even upload files from users!
๐ How to Use the fs Module in Node.js
Letโs get started by creating a Node.js project:
bashCopyEditmkdir file-system-app
cd file-system-app
npm init -y
Create a file:
bashCopyEdittouch index.js
Now, inside index.js, weโll start using the built-in fs module.
jsCopyEditconst fs = require('fs');
๐ That’s it! Now we can start reading and writing files.
๐ 1. Reading Files in Node.js
There are 2 ways to read files:
๐ Synchronous (Blocking) โ fs.readFileSync
jsCopyEditconst data = fs.readFileSync('example.txt', 'utf-8');
console.log(data);
Vikas Sankhla is a seasoned Full Stack Developer with over 7 years of experience in web development. He is the founder of Web Codder, a platform dedicated to providing comprehensive web development tutorials and resources. Vikas specializes in the MERN stack (MongoDB, Express.js, React.js, Node.js) and has been instrumental in mentoring aspiring developers through his online courses and content. His commitment to simplifying complex web technologies has made him a respected figure in the developer community.