🗂️ 3.8 Working with File Systems in Node.js — Reading, Writing & Uploading Files Made Easy

Table of Contents

Hey there, lil’ coder! 👋

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);
  • This stops the program until the file is read.
  • Use it for small scripts.

🔁 Asynchronous (Non-blocking) – fs.readFile

jsCopyEditfs.readFile('example.txt', 'utf-8', (err, data) => {
  if (err) return console.error(err);
  console.log(data);
});
  • Doesn’t block the rest of your app.
  • Best for web servers or large files.

📦 Let’s Create a Test File

Create a file called example.txt:

perlCopyEditThis is my first file read in Node.js 🚀

Now run your script. You’ll see the message in your terminal!

🧠 Tip: Always use async methods in real apps. They’re faster and safer!


✍️ 2. Writing Files in Node.js

You can create or replace a file using fs.writeFile:

jsCopyEditfs.writeFile('newFile.txt', 'Hello from Web Codder! 🧡', (err) => {
  if (err) throw err;
  console.log('✅ File written successfully!');
});
  • If the file doesn’t exist, Node creates it.
  • If it exists, the content gets replaced.

➕ 3. Appending Data to a File

Want to add more data to an existing file? Use fs.appendFile:

jsCopyEditfs.appendFile('newFile.txt', '\nAnother line from Web Codder 🔥', (err) => {
  if (err) throw err;
  console.log('✅ Data appended!');
});

🔍 \n adds a new line between entries.


🧨 4. Deleting a File

Want to remove a file?

jsCopyEditfs.unlink('newFile.txt', (err) => {
  if (err) throw err;
  console.log('🗑️ File deleted!');
});

Be careful — once deleted, it’s gone! 😅


🧺 5. Handling File Uploads with Multer

Now let’s make it fancy 🎩

Imagine your app lets users upload profile pictures.
You’ll need a way to receive and save uploaded files.

Here comes multer — a popular middleware for handling file uploads in Express apps.

📦 Install multer:

bashCopyEditnpm install express multer

🛠️ Basic File Upload Setup

jsCopyEditconst express = require('express');
const multer = require('multer');
const app = express();

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, 'uploads/'),
  filename: (req, file, cb) => cb(null, Date.now() + '-' + file.originalname)
});

const upload = multer({ storage });

app.post('/upload', upload.single('myFile'), (req, res) => {
  res.send('✅ File uploaded successfully!');
});

app.listen(3000, () => console.log('Server running on port 3000'));

📁 Folder Structure After Upload

pgsqlCopyEditfile-system-app/
├── index.js
├── uploads/
│   └── 1715087731873-profile.jpg

🧠 Multer saves your uploaded files to the uploads/ folder.

File Upload Vuln Pic 4
🗂️ 3.8 Working With File Systems In Node.js — Reading, Writing & Uploading Files Made Easy 2


✅ Recap — What You Learned Today

ConceptCode Example
Read File (Sync)fs.readFileSync()
Read File (Async)fs.readFile()
Write Filefs.writeFile()
Append Filefs.appendFile()
Delete Filefs.unlink()
Upload Filemulter.upload.single()

You’re now a file-system ninja! 🥷


🛠️ Project Ideas to Practice

  • 📓 Build a simple Notepad that writes to .txt files
  • 📷 Image gallery where users upload and view pictures
  • 📂 Backup tool that saves server logs daily

📣 Stay Connected with Web Codder

Want more awesome tutorials and beginner-friendly guides?

📺 Subscribe to Web Codder on YouTube
📸 Follow us on Instagram
💬 Join our WhatsApp Community

Let’s keep learning and building together! 💡💻

Share the Post:
Picture of Web Codder

Web Codder

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.

Related Posts