Skip to content

Repository files navigation

05_node.js

🌐 Create a Server & Read/Write File in Node.js

यह example दिखाता है कि कैसे Node.js में एक HTTP server बनाया जाए और fs module का इस्तेमाल करके file read/write किया जाए।

Example Code

consthttp=require('http');constfs=require('fs');// Create HTTP Serverconstserver=http.createServer((req,res)=>{if(req.url==='/write'){// Write to filefs.writeFile('example.txt','Hello from Node.js!',(err)=>{if(err){res.writeHead(500,{'Content-Type': 'text/plain'});returnres.end('❌ Error writing file.');}res.writeHead(200,{'Content-Type': 'text/plain'});res.end('✅ File written successfully.');});}elseif(req.url==='/read'){// Read filefs.readFile('example.txt','utf8',(err,data)=>{if(err){res.writeHead(500,{'Content-Type': 'text/plain'});returnres.end('❌ Error reading file.');}res.writeHead(200,{'Content-Type': 'text/plain'});res.end(`📄 File Content: ${data}`);});}else{// Default Routeres.writeHead(200,{'Content-Type': 'text/plain'});res.end('Welcome! Use /write to create a file and /read to read it.');}});// Start ServerconstPORT=3000;server.listen(PORT,()=>{console.log(`🚀 Server running at http://localhost:${PORT}`);});

"Node.js HTTP Server with Multiple Pages, Common Header, and CSS Support"

📂 Project Structure


project-folder/
│
├── server.js
└── pages/
├── header.html
├── footer.html
├── index.html
├── about.html
├── contact.html
└── style.css

Code

consthttp=require('http');constfs=require('fs');constpath=require('path');constPORT=3000;http.createServer((req,res)=>{letfilePath='';letcontentType='text/html';// Common header and footerconstheaderHTML=fs.readFileSync(path.join(__dirname,'pages','header.html'),'utf-8');constfooterHTML=fs.readFileSync(path.join(__dirname,'pages','footer.html'),'utf-8');// Routingif(req.url==='/'||req.url==='/index'){filePath=path.join(__dirname,'pages','index.html');}elseif(req.url==='/about'){filePath=path.join(__dirname,'pages','about.html');}elseif(req.url==='/contact'){filePath=path.join(__dirname,'pages','contact.html');}elseif(req.url==='/style.css'){filePath=path.join(__dirname,'pages','style.css');contentType='text/css';}else{res.writeHead(404,{'Content-Type': 'text/plain'});res.end('404 Page Not Found');return;}// Read and send the filefs.readFile(filePath,'utf-8',(err,data)=>{if(err){res.writeHead(500,{'Content-Type': 'text/plain'});res.end('Internal Server Error');}else{res.writeHead(200,{'Content-Type': contentType});if(contentType==='text/html'){res.write(headerHTML+data+footerHTML);}else{res.write(data);}res.end();}});}).listen(PORT,()=>{console.log(`Server running at http://localhost:${PORT}`);});

Header File

<!DOCTYPE html><html><head><metacharset="UTF-8"><title>My Website</title><linkrel="stylesheet" href="/style.css"></head><body><header><h1>My Node.js Website</h1><nav><ahref="/">Home</a> |
<ahref="/about">About</a> |
<ahref="/contact">Contact</a></nav></header><hr>

Footer File

<hr><footer><p>&copy; 2025 My Website. All Rights Reserved.</p></footer></body></html>

index File

<main><h2>Welcome to the Home Page</h2><p>This is the homepage of our simple Node.js website.</p></main>

about File

<main><h2>About Us</h2><p>We are learning Node.js server-side rendering with static files.</p></main>

contact file

<main><h2>Contact Us</h2><p>Email: example@example.com</p></main>

css file

body {
font-family: Arial, sans-serif;
margin:20px;
background:#f2f2f2;
}
header,footer {
background:#333;
color: white;
padding:10px;
}
headera {
color: yellow;
text-decoration: none;
margin:05px;
}
headera:hover {
text-decoration: underline;
}
main {
padding:10px;
background: white;
border-radius:5px;
}

Run Project

through node

node server.js

Run with Nodemon

Install nodemon globally (only first time):
 npm install -g nodemon
Start the server with nodemon:
 nodemon server.js

📂 File System Related Error Codes

Error CodeMeaningWhen It Happens
ENOENTNo such file or directoryJab file/directory exist nahi karti.
EACCESPermission deniedJab file/directory par access permission nahi hota.
EEXISTFile already existsJab file/directory create karte time wo already exist kare.
ENOTDIRNot a directoryJab path directory hona chahiye par file nikle.
EISDIRIs a directoryJab path file hona chahiye par directory ho.
EMFILEToo many open filesJab ek time par system me zyada files open ho jati hain.
EBADFBad file descriptorJab galat file descriptor ka use hota hai.

🌐 Network Related Error Codes

Error CodeMeaningWhen It Happens
EADDRINUSEAddress already in useJab server ka port already kisi aur process dwara use ho.
ECONNREFUSEDConnection refusedJab server request accept nahi karta.
ECONNRESETConnection reset by peerJab connection abruptly close ho jata hai (server ya client).
ETIMEDOUTConnection timed outJab network request ka response time se nahi milta.
EHOSTUNREACHHost unreachableJab destination host network me available nahi hai.
ENETUNREACHNetwork unreachableJab destination network tak pahunch nahi ho rahi.

⚙️ Process & System Related Error Codes

Error CodeMeaningWhen It Happens
ENOMEMNot enough memoryJab system memory khatam ho jaye.
EFAULTBad addressJab invalid memory address access hota hai.
ESRCHNo such processJab diye gaye PID ka process exist nahi karta.
EPIPEBroken pipeJab stream close hone ke baad usme likhne ki koshish ho.
EINVALInvalid argumentJab kisi function ko galat argument diya jata hai.
EPERMOperation not permittedJab operation ke liye permission nahi hai.

🛠 How to Handle Specific Errors in Node.js

Node.js में errors को handle करने के लिए आपको try...catch blocks (async/await के साथ) या callback में error parameter check करना होता है।

Example: Handling File System Errors

constfs=require('fs');try{fs.readFileSync('data.txt','utf8');console.log('File read successfully');}catch(err){if(err.code==='ENOENT'){console.error('❌ File not found. Please check the file path.');}elseif(err.code==='EACCES'){console.error('❌ Permission denied. Please check file permissions.');}else{console.error('⚠️ An unexpected error occurred:',err);}}

Example: Handling Network Errors

consthttp=require('http');constreq=http.get('http://localhost:5000',(res)=>{console.log(`✅ Status Code: ${res.statusCode}`);});req.on('error',(err)=>{if(err.code==='ECONNREFUSED'){console.error('❌ Connection refused. Is the server running?');}elseif(err.code==='ETIMEDOUT'){console.error('❌ Request timed out.');}else{console.error('⚠️ Network error:',err);}});

Example: Handling Process & System Errors

try{process.kill(99999);// Invalid PID}catch(err){if(err.code==='ESRCH'){console.error('❌ Process not found.');}elseif(err.code==='EPERM'){console.error('❌ Permission denied to kill the process.');}else{console.error('⚠️ System error:',err);}}

About

This repository contains a collection of practice projects, examples, and exercises focused on Express.js, a minimal and flexible Node.js web application framework. Ideal for developers looking to build RESTful APIs and backend services.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages