2. Path module , File system and http module - Node.js
Path Module
The
pathmodule is used to work with file and directory paths. It provides utilities for handling and transforming file paths in a way that works across operating systems (Windows\vs Linux/).
const path = require('path')
console.log("Directory name: " , path.dirname(__filename));
console.log("File name: ", path.basename(__filename))
console.log("File extension: ", path.extname(__filename))
const joinPath = path.join("/user" , "document" , "node", "projects")
console.log("Joined Path" , joinPath)
//OUTPUT
Directory name: C:\Users\rajpu\Desktop\NODE.JS\path-module
File name: index.js
File extension: .js
Joined Path \user\document\node\projects
File System
The
fsmodule lets you interact with the file system (read, write, update, delete files/folders). It supports both synchronous and asynchronous (callback/promise) methods.fs.readFile(path, callback)→ Reads file (async).fs.readFileSync(path)→ Reads file (sync).fs.writeFile(path, data, callback)→ Creates/writes file.fs.appendFile(path, data, callback)→ Appends to a fileconst fs = require('fs') const path = require('path') const dataFolder = path.join(__dirname , "data") // dir name meh aage data folder jod diya if(!fs.existsSync(dataFolder)){ fs.mkdirSync(dataFolder); console.log("Folder is created in current directary") } // Synchorunous way to create file const filePath = path.join(dataFolder , "example.txt") fs.writeFileSync(filePath , "Hello from nodejs") // data naame ke folder ke andr exapmple.txt ban jaaygi uske ande hello from node.js likh jaayga console.log("file created sucessfully") const readContentFromFile = fs.readFileSync(filePath , "utf8") console.log("File Content: " , readContentFromFile) fs.appendFileSync(filePath , "\n THis is a new line added to the file") console.log("New file content: added" ) //Asymshronous way to create file const asyncFilePath = path.join(dataFolder , "asyc-file.txt"); fs.writeFile(asyncFilePath , "Hello Async Node js" , (err)=>{ if(err) throw err; console.log("Asycn file is created sucssfully") fs.readFile(asyncFilePath , 'utf8' , (err , data)=>{ if(err) throw err console.log("Asycn file content: ",data) }) })
HTTP Module (
http)The
httpmodule is used to create an HTTP server and handle requests/responses. It is the foundation for creating web servers in Node.js.http.createServer((req, res) => {})→ Creates a server.req.url→ URL requested.req.method→ HTTP method (GET,POST, etc.).res.writeHead(statusCode, headers)→ Set status + headers.res.end(data)→ Send response.const http = require('http') const server = http.createServer((req,res)=>{ console.log(req,"req") res.writeHead(200, {"content-type": "text/plain"}); res.end("Hello nodejs from http module") // this will came in our browser when we run localhost:3000 }) server.listen(3000 , ()=>{ console.log("Server is running at port 3000") })How to create routes in https server -: ?
const http = require('http') const server = http.createServer((req,res)=>{ const url = req.url // giev current url of route on which we are having if(url === "/"){ res.writeHead(200 , {"content-type": "text/plain"}); res.end("Home Page"); //http://localhost:3000/ } else if(url === "/projects"){ res.writeHead(200 , {"content-type": "text/plain"}); res.end("Projects Page"); //http://localhost:3000/projects } else{ res.writeHead(404 , {"content-type": "text/plain"}); res.end("Page Not Found"); //http://localhost:3000/pppppzxoxxn } }) server.listen(3000 , ()=>{ console.log("Server runs at 3000") })