0% found this document useful (0 votes)
3 views16 pages

Node Module3 FileSystem

Module 3 of the MERN Stack course focuses on the Node.js File System (fs) module, covering essential operations such as reading, writing, and appending files, as well as using JSON as a mini-database. It emphasizes the importance of understanding synchronous vs asynchronous operations and provides practical examples for real-world applications like logging and handling uploads. The module concludes with common mistakes to avoid and practice tasks to reinforce learning.

Uploaded by

vischiragjain
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

Node Module3 FileSystem

Module 3 of the MERN Stack course focuses on the Node.js File System (fs) module, covering essential operations such as reading, writing, and appending files, as well as using JSON as a mini-database. It emphasizes the importance of understanding synchronous vs asynchronous operations and provides practical examples for real-world applications like logging and handling uploads. The module concludes with common mistakes to avoid and practice tasks to reinforce learning.

Uploaded by

vischiragjain
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

M E R N S TA C K — N O D E .

J S F O U N D AT I O N

Module 3: File System (fs)


Files padhna, likhna, aur JSON ko ek 'mini-database' ki
tarah use karna — MongoDB aane se pehle ka pehla kadam.

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327


ROADMAP

Is Module Mein Kya Kya Cover Hoga

1 2
Sync vs Async — Node ka core concept Files padhna aur likhna

3 4
Files mein append karna JSON ko mini-database ki tarah use karna

5 6
Directories, existence check, delete fs/promises + real-world mini CRUD

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 2


QUICK RECAP

Module 2 Se Yaad Hai?


• require/[Link] aur import/export se code ko multiple files mein organize karna seekha.
• Ab tak humara saara data (jaise students array) code ke ANDAR hi hardcoded tha.
• Real backend mein data kahin 'persist' (save) hona chahiye — page/server restart hone ke baad bhi wahan rahe.
• MongoDB seekhne se pehle, chalo dekhte hain — sabse simple storage: files. Isko Node ka fs (File System) module handle karta hai.

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 3


REAL WORLD

fs Module Real Mein Kahan Use Hota Hai

📄 Logs Likhna
Server errors ya activity ko ek log file mein save karna

⚙️ Config Padhna
Settings ek .json file se load karna

🖼️ Uploads Handle Karna


User ki uploaded image/file ko server pe save karna

💾 Chhota Data Store


Bina database ke, JSON file mein data rakhna (aaj yehi seekhenge)

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 4


CORE CONCEPT

Sync vs Async — Sabse Zaroori Concept


fs ke har function ke DO versions hote hain — jaise readFile aur readFileSync. Farak samjho:

Sync (readFileSync) Async (readFile)

Poora Node ROOK jaata hai jab tak file poori padh na le. Baaki koi File padhna 'background' mein shuru hota hai, Node turant aage badh
kaam nahi hota tab tak — 'blocking'. jaata hai. Jab file padh li jaati hai, ek callback function chalta hai —
'non-blocking'.
Chhote scripts ke liye theek, par server mein DANGEROUS — sab
requests ruk jayengi. Servers ke liye ye hi sahi tarika hai.

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 5


READING

Files Padhna — readFile vs readFileSync


Async (callback ke saath) Sync (seedha return)

const fs = require('fs') const fs = require('fs')

[Link]('[Link]', 'utf8', (err, data) => { try {


if (err) { const data = [Link](
[Link](err) '[Link]', 'utf8'
return )
} [Link](data)
[Link](data) } catch (err) {
}) [Link](err)
}

'utf8' encoding batao, warna raw Buffer milega (binary data) — text nahi.

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 6


WRITING

Files Likhna — writeFile


Agar file exist nahi karti, Node khud bana deta hai. Agar exist karti hai, poora content REPLACE ho jaata hai.

const fs = require('fs')

// Async
[Link]('[Link]', 'Namaste!', (err) => {
if (err) throw err
[Link]("File save ho gayi!")
})

// Sync
[Link]('[Link]', 'Namaste!')

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 7


APPENDING

Content Jodna — appendFile


writeFile poora replace karta hai — agar sirf ANT mein kuch jodna hai (jaise log entry), appendFile use karo.

const fs = require('fs')

function logMessage(msg) {
const entry = `${new Date().toISOString()} - ${msg}\n`
[Link]('[Link]', entry, (err) => {
if (err) [Link](err)
})
}

logMessage("Server started")
logMessage("New student added")

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 8


THE PATTERN

JSON File — Mini Database


Ye pattern bahut common hai: read → [Link] → JS mein modify karo → [Link] → write.

// [Link] → [{ "id": 1, "name": "Ananya" }]

const raw = [Link]('[Link]', 'utf8')


const students = [Link](raw) // text → JS array

[Link]({ id: 2, name: "Rahul" })

[Link](
'[Link]',
[Link](students, null, 2) // pretty-print
)

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 9


MORE BASICS

File Hai Ya Nahi? Delete Kaise Karein?

const fs = require('fs')

// Check karo file hai ya nahi


if ([Link]('[Link]')) {
[Link]("File exist karti hai")
}

// Delete karo
[Link]('[Link]', (err) => {
if (err) [Link](err)
[Link]("Delete ho gayi")
})

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 10


DIRECTORIES

Folders Ke Saath Kaam Karna

// Naya folder banao


[Link]('uploads')

// Folder ke andar kya kya hai, list karo


const files = [Link]('uploads')
[Link](files) // ['[Link]', '[Link]']

// Folder pehle se hai to error na aaye:


[Link]('uploads', { recursive: true })

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 11


THE MODERN WAY

fs/promises — Cleaner Async Code


Callbacks kaam karte hain, par nested ho jaayein to padhna mushkil. fs/promises se async/await use kar sakte ho — agla module mein async/await
poori tarah cover hoga.

const fs = require('fs/promises')

async function getStudents() {


const raw = await [Link]('[Link]', 'utf8')
return [Link](raw)
}

getStudents().then((students) => [Link](students))

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 12


PUT IT TOGETHER

Real Example — [Link] Mini CRUD


Ek chhota module jo add/get students file se karta hai — bilkul waisa hi jaisa MongoDB ke saath aage karenge.

// [Link]
const fs = require('fs')
const FILE = '[Link]'

function getAll() {
if (![Link](FILE)) return []
return [Link]([Link](FILE, 'utf8'))
}

function addStudent(student) {
const students = getAll()
[Link](student)
[Link](FILE, [Link](students, null, 2))
}

[Link] = { getAll, addStudent }


Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 13
WATCH OUT

Common fs Mistakes


Server code mein readFileSync overuse karna

Fix: har request pe blocking calls server ko slow kar sakte hain — async ya fs/promises use karo


'utf8' encoding dena bhool jaana

Fix: bina encoding ke Buffer milta hai, text nahi — readFile(path, 'utf8')


[Link] se pehle [Link] karna bhool jaana (ya ulta)

Fix: file mein hamesha STRING jaata hai — object ko stringify karke likho


Error handling skip karna (file exist hi na ho)

Fix: try/catch ya callback ke err parameter ko hamesha check karo

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 14


WRAP UP

Quick Recap + Practice Task


• Sync = blocking (poora ruk jaata hai), Async = non-blocking (background
mein)
• readFile/writeFile — files padhna, likhna
🎯 PRACTICE TASK
• appendFile — end mein jodna
• [Link] + [Link] se JSON files ko 'mini-database' banaya 1. Ek [Link] banao aur usme apna naam likho

• existsSync, unlink, mkdir, readdir


2. Usi file mein 2-3 aur lines appendFile se jodo
• fs/promises se async/await wala cleaner code

3. Ek [Link] banao, kuch students likho, phir Node se


read karke [Link] karo

4. Bonus: [Link] jaisa module banao jo add/get kar


sake

Next Module → Async JavaScript + Event Loop

Ycotes Computer Classes | Prepared by Chirag Sir | +91 9216988327 15


Shukriya!
Questions? Doubts? Comment ya class mein poocho.
Agle module mein milte hain — Async JS + Event Loop ke saath.

YC OT E S C O M P U T E R C L A S S E S

You might also like