Full Stack Development (MERN)-CS631PE Department of CSE
Unit -2
1. Working with JSON in Node.js
JSON (JavaScript Object Notation) is a lightweight format for storing and transporting data. In
Node.js, it's commonly used for configuration files, APIs, and data exchange.
Key Operations:
• JSON.stringify(): Converts a JavaScript object to a JSON string.
• JSON.parse(): Converts a JSON string back to a JavaScript object.
Example:
const user = { name: "Sai", age: 25 };
// Convert object to JSON string
const jsonString = JSON.stringify(user);
console.log(jsonString); // {"name":"Sai","age":25}
// Convert JSON string back to object
const parsedUser = JSON.parse(jsonString);
console.log(parsedUser.name); // Sai
This is especially useful when sending or receiving data via HTTP or saving to files.
2. Using the Buffer Module to Buffer Data
Buffers are used to handle binary data directly in memory. This is essential when working with
streams, files, or network protocols.
Why Buffers?
JavaScript strings are UTF-16 encoded, but binary data (like images or files) needs byte-level
manipulation. Buffers provide that low-level access.
Creating Buffers:
const buf = Buffer.from("Hello, Sai!");
console.log(buf); // <Buffer 48 65 6c 6c 6f 2c 20 53 61 69 21>
console.log(buf.toString()); // Hello, Sai!
Convert JSON to Buffer and Back:
const obj = { message: "Hello" };
const buffer = Buffer.from(JSON.stringify(obj));
const restored = JSON.parse(buffer.toString());
console.log(restored.message); // Hello
Buffers are also used in file I/O and network communication for performance and memory
efficiency.
3. Using the Stream Module to Stream Data
Streams allow you to process data piece by piece instead of loading it all at once—perfect for
large files or real-time data.
Types of Streams:
• Readable: For reading data (e.g., from a file).
• Writable: For writing data (e.g., to a file).
• Duplex: Both readable and writable.
• Transform: Modifies data as it’s read or written.
Reading a File with Streams:
const fs = require("fs");
const readStream = fs.createReadStream("input.txt", "utf8");
22
Full Stack Development (MERN)-CS631PE Department of CSE
readStream.on("data", chunk => {
console.log("Chunk received:", chunk);
});
readStream.on("end", () => {
console.log("Finished reading.");
});
Writing to a File with Streams:
const writeStream = fs.createWriteStream("output.txt");
writeStream.write("Hello, Sai!\n");
writeStream.write("Streaming is efficient.\n");
writeStream.end();
This approach is memory-efficient and ideal for handling large datasets or real-time
applications like video streaming or chat servers.
1. Importing the File System Module
const fs = require("fs");
2. Creating or Opening a File
Using fs.open()
Opens a file for reading or writing. If it doesn’t exist, it creates one.
fs.open("example.txt", "w", (err, file) => {
if (err) throw err;
console.log("File opened or created!");
});
• "w" means write mode. Other flags include "r" (read), "a" (append), etc.
3. Writing to a File
Using fs.writeFile()
Overwrites the file or creates it if it doesn’t exist.
fs.writeFile("example.txt", "Hello, Sai!", err => {
if (err) throw err;
console.log("File written successfully!");
});
Using fs.appendFile()
Adds content to the end of the file.
fs.appendFile("example.txt", "\nAppended line.", err => {
if (err) throw err;
console.log("Content appended!");
});
4. Reading from a File
Using fs.readFile()
Reads the entire file asynchronously.
23
Full Stack Development (MERN)-CS631PE Department of CSE
fs.readFile("example.txt", "utf8", (err, data) => {
if (err) throw err;
console.log("File content:\n", data);
});
5. Closing a File
When using fs.open(), you can close the file descriptor manually:
fs.open("example.txt", "r", (err, fd) => {
if (err) throw err;
console.log("File opened!");
fs.close(fd, err => {
if (err) throw err;
console.log("File closed!");
});
});
6. Deleting a File
Using fs.unlink()
fs.unlink("example.txt", err => {
if (err) throw err;
console.log("File deleted!");
});
7. Other File System Tasks
Renaming a File
fs.rename("oldname.txt", "newname.txt", err => {
if (err) throw err;
console.log("File renamed!");
});
Checking if a File Exists
fs.access("example.txt", fs.constants.F_OK, err => {
console.log(err ? "File does not exist" : "File exists");
});
Bonus: Using Promises with fs.promises
const fsPromises = require("fs").promises;
async function readFileAsync() {
try {
const data = await fsPromises.readFile("example.txt", "utf8");
console.log(data);
} catch (err) {
console.error(err);
}
}
readFileAsync();
24
Full Stack Development (MERN)-CS631PE Department of CSE
Implementing HTTP services in Node.js involves handling requests, processing URLs, and
responding to clients efficiently. Let’s break it down step by step:
1. Setting Up an HTTP Server
Node.js provides the built-in http module to create an HTTP server.
Example: Basic HTTP Server
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, Sai! Welcome to Node.js HTTP services.");
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• http.createServer() creates a server.
• res.writeHead(200, { "Content-Type": "text/plain" }) sets the response header.
• res.end() sends the response and closes the connection.
• server.listen(3000) starts the server on port 3000.
2. Processing URLs in Node.js
To extract and process URL parameters, we use the url module.
Example: Parsing URL Parameters
const http = require("http");
const url = require("url");
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const name = parsedUrl.query.name || "Guest";
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Hello, ${name}!`);
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• url.parse(req.url, true) extracts query parameters.
• parsedUrl.query.name retrieves the name parameter from the URL.
• Example request: http://localhost:3000/?name=Sai → Response: "Hello, Sai!"
3. Handling Different Routes
You can define multiple routes to serve different responses.
Example: Routing Requests
const http = require("http");
const url = require("url");
25
Full Stack Development (MERN)-CS631PE Department of CSE
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
res.writeHead(200, { "Content-Type": "text/plain" });
if (pathname === "/about") {
res.end("Welcome to the About Page!");
} else if (pathname === "/contact") {
res.end("Contact us at contact@example.com");
} else {
res.end("Home Page");
}
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• pathname === "/about" serves the About page.
• pathname === "/contact" serves the Contact page.
• Default response serves the Home page.
4. Handling POST Requests
For handling form submissions or API requests, use req.on("data") to process incoming data.
Example: Handling POST Data
const http = require("http");
const server = http.createServer((req, res) => {
if (req.method === "POST") {
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Received Data: ${body}`);
});
} else {
res.writeHead(405, { "Content-Type": "text/plain" });
res.end("Only POST requests are allowed.");
}
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
26
Full Stack Development (MERN)-CS631PE Department of CSE
});
• req.on("data", chunk => { body += chunk; }) collects incoming data.
• req.on("end", () => { res.end(body); }) sends the processed data back.
5. Using Express for Simplified HTTP Services
Instead of manually handling requests, Express.js makes routing easier.
Example: Express Server with Routes
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("Home Page"));
app.get("/about", (req, res) => res.send("About Page"));
app.post("/submit", (req, res) => res.send("Form Submitted"));
app.listen(3000, () => console.log("Express server running on http://localhost:3000"));
• app.get("/about", (req, res) => res.send("About Page")) handles GET requests.
• app.post("/submit", (req, res) => res.send("Form Submitted")) handles POST requests.
Processing Query Strings and Form Parameters
Processing query strings and form parameters in Node.js is essential for handling user input
in web applications. Let’s break it down step by step with examples.
1. Understanding Query Strings
Query strings are appended to URLs after a ? and contain key-value pairs separated by &.
Example URL with Query String:
http://localhost:3000/?name=Sai&age=25
Here, name=Sai and age=25 are query parameters.
Extracting Query Parameters in Node.js
Using the built-in url module:
const http = require("http");
const url = require("url");
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const queryParams = parsedUrl.query;
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Hello, ${queryParams.name}! You are ${queryParams.age} years old.`);
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• url.parse(req.url, true) extracts query parameters.
• parsedUrl.query holds the key-value pairs.
2. Using the querystring Module
27
Full Stack Development (MERN)-CS631PE Department of CSE
The querystring module provides utilities for parsing and formatting query strings.
Parsing Query Strings
const querystring = require("querystring");
const query = "name=Sai&age=25";
const parsedQuery = querystring.parse(query);
console.log(parsedQuery.name); // Sai
console.log(parsedQuery.age); // 25
Stringifying Objects into Query Strings
const obj = { name: "Sai", age: 25 };
const queryString = querystring.stringify(obj);
console.log(queryString); // "name=Sai&age=25"
This is useful when constructing URLs dynamically.
3. Handling Form Parameters in Node.js
Form data is sent via POST requests and must be processed from the request body.
Example: Handling Form Data
const http = require("http");
const server = http.createServer((req, res) => {
if (req.method === "POST") {
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
const parsedBody = querystring.parse(body);
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Received: ${parsedBody.name}, Age: ${parsedBody.age}`);
});
} else {
res.writeHead(405, { "Content-Type": "text/plain" });
res.end("Only POST requests are allowed.");
}
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• req.on("data", chunk => { body += chunk; }) collects incoming data.
• querystring.parse(body) converts form data into an object.
4. Using Express for Easier Form Handling
28
Full Stack Development (MERN)-CS631PE Department of CSE
Instead of manually parsing data, Express.js simplifies form handling.
Example: Handling Query Strings in Express
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send(`Hello, ${req.query.name}! You are ${req.query.age} years old.`);
});
app.listen(3000, () => console.log("Express server running on http://localhost:3000"));
• req.query.name extracts query parameters.
Example: Handling Form Data in Express
const express = require("express");
const app = express();
app.use(express.urlencoded({ extended: true }));
app.post("/submit", (req, res) => {
res.send(`Received: ${req.body.name}, Age: ${req.body.age}`);
});
app.listen(3000, () => console.log("Express server running on http://localhost:3000"));
• express.urlencoded({ extended: true }) parses form data automatically.
Understanding Request, Response, and Server Objects in node js with detail explanation
1. Server Object in Node.js
The server object represents an HTTP server that listens for incoming requests and sends
responses.
Creating a Basic Server
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, Sai! Welcome to Node.js HTTP services.");
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• http.createServer() creates an HTTP server.
• res.writeHead(200, { "Content-Type": "text/plain" }) sets the response header.
• res.end() sends the response and closes the connection.
• server.listen(3000) starts the server on port 3000.
29
Full Stack Development (MERN)-CS631PE Department of CSE
2. Request Object (req)
The request object contains details about the incoming HTTP request, such as method,
headers, and query parameters.
Extracting Request Details
const http = require("http");
const server = http.createServer((req, res) => {
console.log("Method:", req.method);
console.log("URL:", req.url);
console.log("Headers:", req.headers);
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Request details logged.");
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• req.method retrieves the HTTP method (GET, POST, etc.).
• req.url provides the requested URL.
• req.headers contains request headers.
3. Processing Query Strings
Query strings are appended to URLs after a ? and contain key-value pairs.
Example URL with Query String
http://localhost:3000/?name=Sai&age=25
Extracting Query Parameters
const url = require("url");
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const queryParams = parsedUrl.query;
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Hello, ${queryParams.name}! You are ${queryParams.age} years old.`);
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• url.parse(req.url, true) extracts query parameters.
• parsedUrl.query holds the key-value pairs.
4. Response Object (res)
The response object is used to send data back to the client.
Sending a JSON Response
const server = http.createServer((req, res) => {
30
Full Stack Development (MERN)-CS631PE Department of CSE
const user = { name: "Sai", age: 25 };
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(user));
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• res.writeHead(200, { "Content-Type": "application/json" }) sets the response type.
• JSON.stringify(user) converts the object into a JSON string.
5. Handling POST Requests
For handling form submissions or API requests, use req.on("data") to process incoming data.
Example: Handling POST Data
const http = require("http");
const server = http.createServer((req, res) => {
if (req.method === "POST") {
let body = "";
req.on("data", chunk => {
body += chunk;
});
req.on("end", () => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Received Data: ${body}`);
});
} else {
res.writeHead(405, { "Content-Type": "text/plain" });
res.end("Only POST requests are allowed.");
}
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• req.on("data", chunk => { body += chunk; }) collects incoming data.
• req.on("end", () => { res.end(body); }) sends the processed data back.
6. Using Express for Simplified HTTP Services
Instead of manually handling requests, Express.js makes routing easier.
Example: Express Server with Routes
const express = require("express");
const app = express();
31
Full Stack Development (MERN)-CS631PE Department of CSE
app.get("/", (req, res) => res.send("Home Page"));
app.get("/about", (req, res) => res.send("About Page"));
app.post("/submit", (req, res) => res.send("Form Submitted"));
app.listen(3000, () => console.log("Express server running on http://localhost:3000"));
• app.get("/about", (req, res) => res.send("About Page")) handles GET requests.
• app.post("/submit", (req, res) => res.send("Form Submitted")) handles POST requests.
Implementing HTTP Clients and Servers in Node.js
Implementing HTTP Clients and Servers in Node.js involves creating a server that listens for
requests and a client that sends requests. Let's break it down step by step.
1. Creating an HTTP Server in Node.js
Node.js provides the built-in http module to create an HTTP server.
Example: Basic HTTP Server
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, Sai! Welcome to Node.js HTTP services.");
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• http.createServer() creates an HTTP server.
• res.writeHead(200, { "Content-Type": "text/plain" }) sets the response header.
• res.end() sends the response and closes the connection.
• server.listen(3000) starts the server on port 3000.
2. Creating an HTTP Client in Node.js
An HTTP client sends requests to a server and processes responses.
Example: Making a GET Request
const http = require("http");
http.get("http://localhost:3000", res => {
let data = "";
res.on("data", chunk => {
data += chunk;
});
res.on("end", () => {
console.log("Response from server:", data);
});
});
• http.get() sends a GET request to the server.
32
Full Stack Development (MERN)-CS631PE Department of CSE
• res.on("data", chunk => { data += chunk; }) collects response data.
• res.on("end", () => { console.log(data); }) logs the final response.
3. Handling Different Routes in the Server
You can define multiple routes to serve different responses.
Example: Routing Requests
const http = require("http");
const url = require("url");
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
res.writeHead(200, { "Content-Type": "text/plain" });
if (pathname === "/about") {
res.end("Welcome to the About Page!");
} else if (pathname === "/contact") {
res.end("Contact us at contact@example.com");
} else {
res.end("Home Page");
}
});
server.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
• pathname === "/about" serves the About page.
• pathname === "/contact" serves the Contact page.
• Default response serves the Home page.
4. Making POST Requests from the Client
For handling form submissions or API requests, use req.on("data") to process incoming data.
Example: Sending a POST Request
const http = require("http");
const data = JSON.stringify({ name: "Sai", age: 25 });
const options = {
hostname: "localhost",
port: 3000,
path: "/submit",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": data.length
}
33
Full Stack Development (MERN)-CS631PE Department of CSE
};
const req = http.request(options, res => {
let responseData = "";
res.on("data", chunk => {
responseData += chunk;
});
res.on("end", () => {
console.log("Response from server:", responseData);
});
});
req.write(data);
req.end();
• http.request(options, callback) sends a POST request.
• req.write(data) sends the request body.
• req.end() completes the request.
5. Using Express for Simplified HTTP Services
Instead of manually handling requests, Express.js makes routing easier.
Example: Express Server with Routes
const express = require("express");
const app = express();
app.use(express.json());
app.get("/", (req, res) => res.send("Home Page"));
app.get("/about", (req, res) => res.send("About Page"));
app.post("/submit", (req, res) => res.json({ message: "Form Submitted", data: req.body }));
app.listen(3000, () => console.log("Express server running on http://localhost:3000"));
• app.get("/about", (req, res) => res.send("About Page")) handles GET requests.
• app.post("/submit", (req, res) => res.json({ message: "Form Submitted", data:
req.body })) handles POST requests.
Using Additional Node.js Modules-Using the OS Module
The OS module in Node.js provides methods to interact with the operating system,
retrieve system information, and manage resources efficiently. Let’s break it down
with detailed explanations and examples.
1. Importing the OS Module
To use the OS module, you need to import it:
const os = require("os");
34
Full Stack Development (MERN)-CS631PE Department of CSE
2. Getting System Information
Check OS Platform
console.log("Platform:", os.platform());
Returns the operating system platform (win32, linux, darwin for macOS).
Check OS Release
console.log("OS Release:", os.release());
Returns the version of the operating system.
Check OS Type
console.log("OS Type:", os.type());
Returns the name of the operating system (Windows_NT, Linux, Darwin).
3. CPU Information
Get CPU Architecture
console.log("CPU Architecture:", os.arch());
Returns the CPU architecture (x64, arm, ia32).
Get CPU Details
console.log("CPU Info:", os.cpus());
Returns an array containing details about each CPU core.
4. Memory Management
Get Total Memory
console.log("Total Memory:", os.totalmem());
Returns the total system memory in bytes.
Get Free Memory
console.log("Free Memory:", os.freemem());
Returns the available memory in bytes.
5. Network Information
Get Hostname
console.log("Hostname:", os.hostname());
Returns the system’s hostname.
Get Network Interfaces
console.log("Network Interfaces:", os.networkInterfaces());
Returns details about network adapters.
6. System Uptime
Get System Uptime
console.log("System Uptime (seconds):", os.uptime());
Returns the system uptime in seconds.
7. User Information
Get Current User Info
console.log("User Info:", os.userInfo());
Returns details about the currently logged-in user.
8. Temporary Directory
Get OS Temporary Directory
console.log("Temp Directory:", os.tmpdir());
Returns the default directory for temporary files.
35