Introduction to Node.js
Node.js is a runtime environment that allows us to run JavaScript outside the browser, mainly on the server.
With Node.js, developers can use the same language—JavaScript—for both the front end and back end, which makes development simpler and quicker.
Node.js is designed to handle many users at the same time without slowing down. It uses a non-blocking and event-driven model, meaning it does not wait for one task to finish before starting another. Instead, it responds to events as they happen. This makes Node.js perfect for applications that require quick responses and continuous communication.
Applications of Node.js
-
Real-time chat applications
-
Video streaming platforms
-
Online gaming servers
-
REST APIs and backend services
-
Single-page applications (SPAs)
-
IoT (Internet of Things) applications
-
Collaborative tools like shared editors or dashboards
Architecture of Node.js
Node.js follows a single-threaded, event-driven architecture:
-
Single Thread
-
Non-blocking I/O
-
Event Loop
-
V8 Engine
This design lets Node.js handle thousands of requests efficiently.
Logic of Node.js
When a request comes in, Node.js does not stop and wait for long tasks. Instead, it quickly sends those tasks to the system to handle in the background. While those tasks run, Node.js continues handling other requests. When the background tasks finish, their results are sent back to the main program using callbacks or promises. This makes Node.js fast, lightweight, and good for real-time applications.
PROGRAMS
1. Write a program to show the workflow of JavaScript code executable by creating web server in
Node.js.
// Import the http module
const http = require('http');
// Create a web server
const server = http.createServer((req, res) => {
// 1. Client sends a request
console.log("A request has been received!");
// 2. Server processes JavaScript code
const message = "Hello! This response is generated by JavaScript running on Node.js.";
// 3. Server sends the response back to the client
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(message);
});
// Start the server on port 3000
server.listen(3000, () => {
console.log("Server is running at http://localhost:3000");
});
How the Workflow Happens
1. Start the Server
Run the file:
2. Client Sends Request
Open browser and go to:
3. Server Executes JavaScript Code
-
Node.js receives the request
-
Executes the callback function in createServer
-
Runs the JavaScript logic
-
Prepares the response
4. Response Sent to Client
You will see:
2. Write a program to transfer data over http protocol using http module.
// Import http module
const http = require('http');
// Create HTTP server
const server = http.createServer((req, res) => {
// Set response header
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Data to transfer over HTTP
const message = "Hello! This data is transferred over HTTP protocol.";
// Send the data to the client
res.write(message);
// End the response
res.end();
});
// Server listens on port 3000
server.listen(3000, () => {
console.log("Server running at http://localhost:3000/");
});
3. Create a text file src.txt and add the following content to it. (HTML, CSS, Javascript,
Typescript, MongoDB, Express.js, React.js, Node.js)
const fs = require('fs');
// Content to write in src.txt
const data = `
HTML
CSS
JavaScript
TypeScript
MongoDB
Express.js
React.js
Node.js
`;
// Create and write to src.txt
fs.writeFile('src.txt', data, (err) => {
if (err) {
console.log("Error writing file:", err);
} else {
console.log("src.txt file created successfully!");
}
});
4. Write a program to parse an URL using URL module.
// Import the URL module
const url = require('url');
// URL to parse
const address = "https://www.example.com/products?category=books&id=10";
// Parse the URL
const parsedURL = url.parse(address, true);
// Display parsed parts
console.log("Protocol:", parsedURL.protocol);
console.log("Host:", parsedURL.host);
console.log("Pathname:", parsedURL.pathname);
console.log("Search Query:", parsedURL.search);
console.log("Query Parameters:", parsedURL.query);
5. Write a program to create an user-defined module and show the workflow of Modularization
of application using Node.js
Create a file named mathModule.js
// mathModule.js
// A user-defined module that exports two functions
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
// Export the functions so other files can use them
module.exports = {
add,
multiply
};
Create another file: app.js
// app.js
// Import the user-defined module
const math = require('./mathModule');
// Use the functions from the module
console.log("Addition:", math.add(10, 20));
console.log("Multiplication:", math.multiply(5, 6));
// Show workflow
console.log("\nThis program demonstrates modularization in Node.js.");
console.log("1. mathModule.js contains reusable functions.");
console.log("2. app.js imports the module using require().");
console.log("3. app.js executes the imported functions.");
Comments
Post a Comment