0% found this document useful (0 votes)
20 views62 pages

PAPER SOLUTIONS

The document covers various aspects of Node.js, including components of NPM, syntax for file operations, database connections, and features of Node.js. It also discusses concepts like REPL, anonymous functions, streams, modules, and provides example programs for creating a Historical Place portal and updating student marks in a database. Additionally, it explains the traditional web server model, event handling, and file system operations, along with comparisons between AngularJS and Node.js.
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)
20 views62 pages

PAPER SOLUTIONS

The document covers various aspects of Node.js, including components of NPM, syntax for file operations, database connections, and features of Node.js. It also discusses concepts like REPL, anonymous functions, streams, modules, and provides example programs for creating a Historical Place portal and updating student marks in a database. Additionally, it explains the traditional web server model, event handling, and file system operations, along with comparisons between AngularJS and Node.js.
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
You are on page 1/ 62

NODEJS PAPER-1

Q-1

a) What are the components of NPM?


NPM (Node Package Manager) consists of:

1. npm CLI: Command-line interface used to interact with NPM.


2. npm registry: A large database of open-source packages.
3. npm packages: Libraries or tools that can be installed and used in Node.js
applications.

b) Write the syntax to read a file asynchronously in Node.js using the fs module.

const fs = require('fs');

fs.readFile('filename.txt', 'utf8', (err, data) => {


if (err) throw err;
console.log(data);
});

c) Explain the syntax for configuring a database connection in a Node.js application.

const mysql = require('mysql');

const connection = mysql.createConnection({


host: 'localhost',
user: 'root',
password: 'yourpassword',
database: 'yourdatabase'
});

connection.connect((err) => {
if (err) throw err;
console.log('Connected to the database!');
});

d) What is NodeJS?
Node.js is a JavaScript runtime built on Chrome's V8 engine that allows the execution of
JavaScript code server-side. It is event-driven, non-blocking, and designed for building
scalable network applications.

e) What is REPL?
REPL (Read-Eval-Print Loop) is an interactive programming environment that allows users
to enter expressions, which are evaluated, and the results are printed. Node.js provides a
REPL for testing JavaScript code in an interactive shell.
f) Define Anonymous function.
An anonymous function is a function that is defined without a name, often passed as an
argument to other functions or used for short-term operations. Example:

const sum = function(a, b) {


return a + b;
};

g) What are the features of Node.js?

1. Non-blocking, event-driven I/O


2. Single-threaded architecture
3. Scalability
4. Cross-platform
5. Fast execution due to V8 engine
6. Large ecosystem of libraries (NPM)

h) Write about arrow function.


Arrow functions are a concise way of writing functions in JavaScript. They do not have their
own this context and inherit this from the enclosing scope. Syntax:

const add = (a, b) => a + b;

i) What are the types of streams in NodeJs?

1. Readable Stream: Used to read data from a source.


2. Writable Stream: Used to write data to a destination.
3. Duplex Stream: Can both read and write data.
4. Transform Stream: A type of duplex stream that modifies the data as it is written or
read.

j) What is a module? List its types.


A module in Node.js is a reusable block of code that encapsulates related functionalities.
Types of modules:

1. Core Modules: Built-in modules (e.g., fs, http, path).


2. Local Modules: Custom modules created by the user.
3. Third-Party Modules: External modules installed via NPM.

Q-2
a) Write a program in Node.js to create a Historical Place portal.

Below is a simple Node.js program that creates a basic Historical Place portal. It allows you
to add and view details of historical places through a basic API.

const express = require('express');


const app = express();
const bodyParser = require('body-parser');

// Middleware to parse JSON bodies


app.use(bodyParser.json());

// In-memory data storage for historical places


let historicalPlaces = [
{ id: 1, name: 'Great Wall of China', country: 'China', description: 'A
series of fortifications made of various materials' },
{ id: 2, name: 'Taj Mahal', country: 'India', description: 'A white
marble mausoleum' },
];

// Route to get all historical places


app.get('/places', (req, res) => {
res.json(historicalPlaces);
});

// Route to add a new historical place


app.post('/places', (req, res) => {
const { name, country, description } = req.body;
const newPlace = {
id: historicalPlaces.length + 1,
name,
country,
description
};
historicalPlaces.push(newPlace);
res.status(201).json(newPlace);
});

// Start server
app.listen(3000, () => {
console.log('Historical Place portal is running on
http://localhost:3000');
});

Explanation:

• We use express for the server and body-parser to parse incoming JSON requests.
• The server stores data in-memory (which is not persistent and will be lost when the
server stops).
• The program exposes two API endpoints: one to get all historical places (GET
/places) and another to add new places (POST /places).
• To test this, you can use Postman or any other API testing tool to make requests.
b) Write a Node.js program that updates the marks of a given student Rno in “student”
table and displays the result.

Assuming you are using MySQL to store student data, the following program updates the
marks of a given student based on their roll number (Rno).

const mysql = require('mysql');

// Set up the database connection


const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'school'
});

// Connect to the database


connection.connect((err) => {
if (err) throw err;
console.log('Connected to the database!');
});

// Function to update student marks


function updateMarks(rno, newMarks) {
const query = `UPDATE student SET marks = ? WHERE Rno = ?`;

connection.query(query, [newMarks, rno], (err, result) => {


if (err) throw err;
console.log('Marks updated successfully!');
console.log(`Updated rows: ${result.affectedRows}`);
});
}

// Update marks for student with Rno 101


updateMarks(101, 85);

// Close the connection


connection.end();

Explanation:

• The code connects to a MySQL database using mysql.createConnection.


• The function updateMarks updates the marks field in the student table for a student
with a specific Rno.
• It uses connection.query to execute the SQL UPDATE query.
• The result will display the number of affected rows, which confirms if the update was
successful.

c) What is the purpose of module.exports in Node.js?

In Node.js, module.exports is used to export functions, objects, or variables from a module


so that they can be imported and used in other files.
• Purpose: It allows different parts of an application to share code and data. By using
module.exports, we can expose the functionality of a file or module for other files to
use.

Example:

// math.js
const add = (a, b) => a + b;
module.exports = add;

// app.js
const add = require('./math');
console.log(add(2, 3)); // Output: 5

In this example:

• module.exports = add makes the add function available to other files.


• require('./math') imports the add function into app.js.

d) Explain the difference between AngularJS and NodeJS

AngularJS and Node.js are both popular JavaScript technologies but serve very different
purposes in web development.

1. AngularJS:
o Type: A client-side framework for building Single Page Applications (SPAs).
o Purpose: AngularJS is used for building the front-end (client-side) of web
applications. It handles rendering views, managing user input, and interacting
with APIs.
o Key Features:
▪ Two-way data binding.
▪ Directives for extending HTML functionality.
▪ Dependency injection to manage services and components.
▪ Used for creating dynamic web applications on the client side.
2. Node.js:
o Type: A server-side runtime environment for JavaScript.
o Purpose: Node.js is used for building the back-end (server-side) of
applications. It runs JavaScript code on the server, handles requests, manages
databases, and more.
o Key Features:
▪ Non-blocking, event-driven I/O model.
▪ Built on the V8 JavaScript engine.
▪ Ideal for building scalable applications with real-time interactions
(e.g., chat applications).
▪ Used for creating APIs, web servers, and back-end logic.

Summary:

• AngularJS is for front-end development.


• Node.js is for back-end development.
• AngularJS runs in the browser, while Node.js runs on the server.

e) What is a listener? Explain the function requestListener() with suitable examples.

A listener in Node.js is a function that is used to handle events that are emitted by
EventEmitter objects. The most common use of listeners is in HTTP servers, where they are
used to handle incoming requests.

The requestListener() function is a callback function that is triggered when an HTTP


request is made to a Node.js server.

Example of requestListener:
const http = require('http');

// Function to handle incoming requests


function requestListener(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
}

// Create an HTTP server and listen on port 3000


const server = http.createServer(requestListener);
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});

Explanation:

• In the code above, requestListener() is a function that receives the HTTP request
(req) and response (res) objects.
• When a request is received, the function is called, and it sends a plain text response
"Hello, World!".
• The server listens for incoming requests on port 3000.

A listener is registered using the .on() method on EventEmitter objects, but in this case,
createServer() automatically registers the requestListener() function to handle HTTP
requests.

Q-3

a) Explain the traditional web server model in detail? List its limitations

The traditional web server model follows a request-response cycle. A client (browser) sends
an HTTP request to the server, which processes the request, performs necessary actions (like
retrieving a file or accessing a database), and then sends back an HTTP response containing
the requested data or a relevant status message.
Working:

1. Client sends request: The client sends an HTTP request for a resource (like a
webpage, image, or data).
2. Server processes request: The web server processes the request, usually by fetching
the requested file or executing a script.
3. Server responds: After processing, the server sends an HTTP response back to the
client, which contains the requested data (HTML, JSON, etc.) or an error message.
4. Connection closes: The connection is typically closed after the response is sent.

Limitations of the Traditional Web Server Model:

1. Blocking I/O: In traditional models, servers process one request at a time. If a request
involves reading from a database or file system, the server is blocked until that
operation is completed.
2. Scalability Issues: For every incoming connection, a new thread or process is created.
This consumes resources, and as traffic grows, the server can become overwhelmed.
3. Concurrency Problems: Handling multiple requests concurrently is inefficient in
traditional server models because the server cannot handle multiple requests at the
same time in a non-blocking way.
4. High Memory Consumption: Since each connection often results in a new thread or
process, memory usage increases significantly with the number of concurrent
connections.

b) Write a Node.js program which will convert the output “SY BBA - CA” into upper-
case and lower-case.

// Original string
const str = "SY BBA - CA";

// Convert to uppercase
const upperCaseStr = str.toUpperCase();

// Convert to lowercase
const lowerCaseStr = str.toLowerCase();

// Output the results


console.log("Uppercase: ", upperCaseStr);
console.log("Lowercase: ", lowerCaseStr);

Explanation:

• toUpperCase() converts all characters in the string to uppercase.


• toLowerCase() converts all characters in the string to lowercase.
• The results are printed using console.log().

c) What is a File System? Explain different operations performed on files.


A file system is a method and structure that an operating system uses to store and organize
files on a storage device (such as a hard drive, SSD, or cloud storage). It manages the
reading, writing, and organizing of data in files.

Common File System Operations:

1. Create a File: This operation creates a new empty file in a specified location.
2. const fs = require('fs');
3. fs.writeFileSync('newFile.txt', 'Hello, world!');
4. Read a File: Reads the content of a file. It can be done synchronously or
asynchronously.
5. const data = fs.readFileSync('newFile.txt', 'utf8');
6. console.log(data);
7. Write to a File: Writing data into a file. This can either overwrite or append data to a
file.
8. fs.appendFileSync('newFile.txt', '\nAppended text');
9. Delete a File: This operation deletes a specified file.
10. fs.unlinkSync('newFile.txt');
11. Rename a File: Renames an existing file.
12. fs.renameSync('oldFile.txt', 'newFile.txt');
13. Check File Status: This operation retrieves metadata about a file, such as its size,
creation date, or permissions.
14. const stats = fs.statSync('newFile.txt');
15. console.log(stats);
16. Directory Operations: File systems allow for the creation, reading, and deletion of
directories.
17. fs.mkdirSync('newDirectory');
18. fs.rmdirSync('newDirectory');

d) What is an Event explained in detail? Explain any two methods of event in detail.

An event in Node.js is an action or occurrence that is detected by the system, which can be
handled by a listener or callback function. Node.js uses an event-driven architecture where
the flow of the application is controlled by events.

Event Handling in Node.js:

1. Event Emitter: Node.js has an EventEmitter class that allows objects to emit events
and register listeners to handle those events.
2. Listener: A listener is a callback function that is triggered when an event occurs.

Example:
const EventEmitter = require('events');
const emitter = new EventEmitter();

// Listener for the 'greet' event


emitter.on('greet', () => {
console.log('Hello, World!');
});

// Emitting the 'greet' event


emitter.emit('greet');

Two Event Methods:

1. emitter.on(event, listener):
o Registers a listener function to handle a specific event.
o Syntax: emitter.on('eventName', callback)
o Example:
o emitter.on('greet', () => {
o console.log('Event emitted!');
o });
o This will execute the callback function when the event 'greet' is emitted.
2. emitter.emit(event, [arg1], [arg2], [...]):
o Triggers an event and executes the listener associated with that event.
o Syntax: emitter.emit('eventName')
o Example:
o emitter.emit('greet');
o This will trigger the 'greet' event and execute the corresponding listener.

e) Write a Node.js program to write data to a file in synchronous and asynchronous


modes.

Synchronous Write:
const fs = require('fs');

// Writing data synchronously to a file


fs.writeFileSync('fileSync.txt', 'This is written synchronously.');
console.log('Data written to file synchronously.');

Asynchronous Write:
const fs = require('fs');

// Writing data asynchronously to a file


fs.writeFile('fileAsync.txt', 'This is written asynchronously.', (err) => {
if (err) throw err;
console.log('Data written to file asynchronously.');
});

Explanation:

1. Synchronous write (writeFileSync) blocks the execution until the operation is


completed, and it writes the data to the file.
2. Asynchronous write (writeFile) allows other code to run while the data is being
written to the file in the background. The callback function is triggered once the
writing process is completed.

Both methods write a string to a file but differ in their blocking/non-blocking behavior.

Q-4
a) Write a Node.js program to create a customer DB and account table (cid, name,
balance) in MySQL.

const mysql = require('mysql');

// Create a connection to the MySQL server


const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password'
});

// Connect to the MySQL server


connection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL server!');

// Create the database 'customerDB'


const createDBQuery = 'CREATE DATABASE IF NOT EXISTS customerDB';
connection.query(createDBQuery, (err, result) => {
if (err) throw err;
console.log('Database created or already exists.');

// Use the newly created database


connection.changeUser({database: 'customerDB'}, (err) => {
if (err) throw err;

// Create the 'account' table


const createTableQuery = `CREATE TABLE IF NOT EXISTS account (
cid INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
balance DECIMAL(10, 2) NOT NULL
)`;

connection.query(createTableQuery, (err, result) => {


if (err) throw err;
console.log('Account table created or already exists.');

// Close the connection


connection.end();
});
});
});
});

Explanation:

• The program connects to MySQL and creates a database customerDB if it doesn't


exist.
• It then creates a table account with columns cid, name, and balance.
• cid is the primary key, which auto-increments with each new entry.
• Finally, the connection to the database is closed.

b) Write a code to perform the following operations on Buffer data – Concat, slice,
compare.
// Creating two Buffers
const buffer1 = Buffer.from('Hello');
const buffer2 = Buffer.from('World');

// Concat: Joining two buffers


const concatBuffer = Buffer.concat([buffer1, buffer2]);
console.log('Concatenated Buffer:', concatBuffer.toString()); // Output:
HelloWorld

// Slice: Extracting part of the buffer


const slicedBuffer = concatBuffer.slice(0, 5);
console.log('Sliced Buffer:', slicedBuffer.toString()); // Output: Hello

// Compare: Comparing two buffers


const comparisonResult = buffer1.compare(buffer2);
if (comparisonResult === 0) {
console.log('Buffers are equal.');
} else if (comparisonResult < 0) {
console.log('Buffer1 comes before Buffer2.');
} else {
console.log('Buffer1 comes after Buffer2.');
}

Explanation:

1. Concat: Combines two Buffers into one.


2. Slice: Extracts a portion of the Buffer.
3. Compare: Compares two Buffers lexicographically and returns:
o 0 if they are equal,
o A negative value if the first Buffer is smaller,
o A positive value if the first Buffer is larger.

c) What is a package in Node.js? Explain with an example.

A package in Node.js is a collection of reusable code that can be installed and used in a
Node.js application. It typically contains a package.json file that describes the package, its
dependencies, and other metadata. Packages are hosted in a public registry like npm (Node
Package Manager).

Example:
// package.json
{
"name": "my-node-app",
"version": "1.0.0",
"description": "A simple Node.js application",
"main": "index.js",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {},
"scripts": {
"start": "node index.js"
},
"author": "Your Name",
"license": "ISC"
}

Explanation:

• The package.json file holds metadata about the application, including dependencies.
• The example above uses the express package, which is a web server framework for
Node.js.
• Dependencies are installed via npm, and Node.js uses them in your code.

You can install a package using the following command:

npm install express

d) Write a Node.js program to search a given word in a file and display the result to
Console.

const fs = require('fs');

// File to search in
const filePath = 'sample.txt';

// Word to search for


const searchWord = 'Node.js';

// Reading the file


fs.readFile(filePath, 'utf8', (err, data) => {
if (err) throw err;

// Check if the word is present in the file


if (data.includes(searchWord)) {
console.log(`The word "${searchWord}" was found in the file.`);
} else {
console.log(`The word "${searchWord}" was not found in the file.`);
}
});

Explanation:

• The program reads a file (sample.txt) asynchronously using fs.readFile().


• It checks if the word "Node.js" exists in the file content and prints a message to the
console accordingly.

e) What are dependencies and devDependencies in package.json file?

In a package.json file, dependencies and devDependencies are two types of dependencies


that are required by a Node.js application.
1. dependencies:

• These are the packages that are needed for the application to run in a production
environment.
• They are installed using the command npm install and are crucial for the
application's functionality.

2. devDependencies:

• These are the packages that are only needed during development (e.g., testing
libraries, build tools).
• They are installed using the command npm install --save-dev and are not needed
for running the application in a production environment.

Example:
{
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"mocha": "^8.0.0",
"chai": "^4.2.0"
}
}

Explanation:

• express is a production dependency because it's needed for the app to run.
• mocha and chai are development dependencies because they are used for testing but
are not needed in production.

Q-5

a) Explain Web Server in detail.

A web server is a software that handles HTTP requests from clients (usually web browsers),
processes them, and serves the requested web pages or data. It acts as a mediator between the
client (browser) and the server-side application (which can involve databases, file systems,
etc.). Web servers are essential for delivering dynamic content (like HTML, images, and
other resources) over the internet.

Key Functions of a Web Server:

1. HTTP Request Handling: The server listens for incoming HTTP requests on a
specific port (usually port 80 for HTTP and 443 for HTTPS).
2. Content Delivery: Based on the request, the server locates the requested resource
(such as a file or data) and sends it back to the client as an HTTP response.
3. Dynamic Content: It can also process dynamic requests (e.g., executing server-side
scripts like PHP, Node.js, or Python) and send the generated content back to the
client.
4. Security: Web servers manage security protocols, including SSL/TLS for encrypted
communication over HTTPS.
5. Logging and Error Handling: They maintain logs for requests and errors, which
help in monitoring and troubleshooting server performance.

Common Web Servers:

• Apache HTTP Server: One of the most widely used open-source web servers.
• Nginx: Known for high performance and efficiency, often used as a reverse proxy or
load balancer.
• Node.js HTTP Server: Can be used to build lightweight and scalable web servers
using JavaScript.

b) What is the difference between Blocking and Non-blocking?

Blocking and non-blocking refer to how operations (such as I/O tasks) are handled by the
program. They are fundamental to understanding the performance of Node.js and how it
handles concurrency.

Blocking:

• Definition: In a blocking operation, the program waits for the operation to complete
before moving on to the next task. The thread or process is "blocked" until the task
finishes.
• Example: Reading a file synchronously in Node.js.
• const fs = require('fs');
• let data = fs.readFileSync('file.txt', 'utf8'); // This will block
until the file is read
• console.log(data); // This will execute after the file has been read
• Effect: Blocking operations can reduce performance and cause delays, especially in
high-concurrency environments, because the program cannot perform other tasks
while waiting.

Non-blocking:

• Definition: In non-blocking operations, the program initiates the task and continues
with other tasks without waiting for the operation to complete. Once the operation
finishes, a callback function is triggered to handle the result.
• Example: Reading a file asynchronously in Node.js.
• const fs = require('fs');
• fs.readFile('file.txt', 'utf8', (err, data) => {
• if (err) throw err;
• console.log(data); // This executes once the file is read
• });
• console.log('This runs before the file is read'); // Non-blocking
execution
• Effect: Non-blocking operations allow the program to perform multiple tasks
simultaneously, increasing efficiency, especially for I/O operations (like file reading,
database querying).

c) Explain the usage of a Buffer class in Node.js?

In Node.js, a Buffer is a built-in class used for handling binary data directly in memory.
Buffers are especially useful when working with streams, binary data, or low-level network
operations, where dealing with raw data is required.

Key Points:

1. Storage of Raw Binary Data: Buffers provide a way to store and manipulate binary
data, which is essential in Node.js since it is often used to interact with streams, files,
and network protocols (e.g., TCP).

Example:

const buffer = Buffer.from('Hello, World!', 'utf8');


console.log(buffer); // Outputs the buffer with binary representation

2. Memory Efficiency: Buffers allow for more efficient memory management


compared to strings, as they don’t require encoding/decoding to and from UTF-8 or
other encodings. This is especially useful when working with large data sets or
handling network responses.
3. Buffer Methods: Buffers come with a variety of methods to manipulate the data:
o Buffer.concat(): Concatenate multiple buffers into one.
o Buffer.slice(): Create a new buffer from a subset of an existing buffer.
o Buffer.compare(): Compare two buffers to determine their lexicographical
order.

Example:

const buf1 = Buffer.from('Hello');


const buf2 = Buffer.from('World');
const concatenated = Buffer.concat([buf1, buf2]);
console.log(concatenated.toString()); // Outputs: HelloWorld

4. Use in Networking and Streams: Buffers are commonly used in network


communication (e.g., reading data from a TCP stream) and file handling where binary
data is processed directly.

Example:

const fs = require('fs');
const buffer = fs.readFileSync('image.png');
console.log(buffer.length); // Logs the length of the binary data
Conclusion:

Buffers in Node.js are crucial for handling raw binary data, providing an efficient way to
store and manipulate such data for high-performance applications like network servers, file
systems, and media processing.

NODEJS PAPER-2

Q-1

a) What is the command to initialize Node Package Manager? Write its syntax.

The command to initialize Node Package Manager (NPM) is:

npm init

Syntax:
npm init [options]

This command initializes a new package.json file, which holds metadata about the project
and its dependencies. You can also use npm init -y to automatically generate the file with
default values.

b) For which task is the file system module used?

The File System (fs) module in Node.js is used for interacting with the file system. It allows
you to perform tasks such as reading, writing, updating, deleting, and manipulating files and
directories.

Example tasks:

• Reading and writing files


• Creating, renaming, or deleting files and directories
• Managing file permissions

c) What is REPL?

REPL stands for Read-Eval-Print Loop. It is an interactive programming environment that


reads user input, evaluates the code, prints the result, and loops back to read the next input. In
Node.js, the REPL is used to interactively test JavaScript code and explore Node.js APIs.

d) What is Express.js?
Express.js is a minimal and flexible web application framework for Node.js. It simplifies the
creation of web servers and APIs by providing robust features like routing, middleware
support, and template engines. Express is widely used for building RESTful APIs and web
applications.

e) What is the use of the prompt-sync module?

The prompt-sync module is used to synchronously prompt the user for input from the
console. It is typically used in CLI (Command Line Interface) applications where the
program waits for user input before proceeding.

Example:

const prompt = require('prompt-sync')();


const name = prompt('What is your name? ');
console.log(`Hello, ${name}!`);

f) List any four core modules in Node.js.

1. fs: File system module, used for file handling.


2. http: Used to create HTTP servers and clients.
3. path: Provides utilities for working with file and directory paths.
4. url: Used for parsing and handling URL-related tasks.

g) Which command is used for deleting a file?

To delete a file in Node.js, you can use the fs.unlink() method:

const fs = require('fs');
fs.unlink('file.txt', (err) => {
if (err) throw err;
console.log('File deleted');
});

Alternatively, you can delete a file from the command line using the rm command:

rm file.txt

h) Write syntax to create Buffer.

You can create a buffer using the Buffer.from(), Buffer.alloc(), or


Buffer.allocUnsafe() methods.
Syntax:
// Creating a buffer from a string
const buf = Buffer.from('Hello, World!', 'utf8');

// Creating a buffer with specified length


const buf2 = Buffer.alloc(10); // Allocates a buffer of 10 bytes, filled
with 0s

// Creating an uninitialized buffer


const buf3 = Buffer.allocUnsafe(10); // May contain old memory data

i) Write a command to install the MySQL package by using NPM.

To install the MySQL package using NPM, use the following command:

npm install mysql

This will add the MySQL package as a dependency to your project, allowing you to interact
with MySQL databases.

Q-2

a) How do we install a package globally in Node.js? Write its command with an


example.

To install a package globally in Node.js, you use the npm install command with the -g
flag. This allows the package to be used anywhere on your system without needing to be
added to each specific project. Global installation is useful for tools or utilities that you want
to use across various projects, such as a build tool or a command-line tool.

Command:
npm install -g <package-name>

Example:

To install the nodemon package globally, which is used for automatically restarting Node.js
applications during development:

npm install -g nodemon

Once installed globally, you can use nodemon from anywhere on your system:

nodemon app.js

This command runs the app.js file and automatically restarts the application whenever the
code changes.
b) What are the advantages of Node.js?

Node.js offers several key advantages, particularly in handling high-performance


applications, and it is well-suited for real-time web applications and services.

Key Advantages:

1. Non-blocking I/O: Node.js uses non-blocking, event-driven architecture, which


allows it to handle multiple requests simultaneously. This increases the efficiency of
applications by not blocking the execution of tasks while waiting for I/O operations to
complete.
2. Single Programming Language (JavaScript): Developers can use JavaScript both
on the client-side and the server-side. This reduces the learning curve and allows for a
more cohesive development experience.
3. Scalability: Node.js is highly scalable and can handle a large number of simultaneous
connections with high throughput, making it suitable for building scalable web
applications, APIs, and microservices.
4. Faster Execution: Since Node.js is built on the V8 JavaScript engine, it can execute
code very quickly, making it ideal for building real-time applications such as chat
applications or live updates.
5. Large Ecosystem (NPM): The Node Package Manager (NPM) provides access to a
vast number of reusable packages and libraries, helping developers save time and
effort when building applications.
6. Cross-platform: Node.js can run on various operating systems like Windows, Linux,
and macOS, providing flexibility to develop and deploy applications across platforms.

c) Explain Node.js Process Model.

The Node.js Process Model is designed to handle concurrent operations in a single-threaded


environment by leveraging an event-driven, non-blocking I/O model. This allows Node.js to
handle multiple operations at once without needing to create new threads for each task.

Process Model Characteristics:

1. Single-Threaded: Node.js runs on a single thread using the event loop to handle
asynchronous operations. This avoids the overhead of managing multiple threads,
making it lightweight and efficient.
2. Event Loop: The event loop is responsible for executing asynchronous callbacks. It
processes events from the event queue and handles I/O operations without blocking
other tasks. The event loop allows Node.js to perform tasks like reading from a file
system or querying a database while other code continues to run.
3. Non-blocking I/O: The non-blocking I/O model ensures that operations like reading
files, accessing databases, or making network requests do not stop the execution of
other code. Instead of waiting for the result, Node.js continues executing the code and
invokes a callback when the task completes.
4. Worker Threads (For CPU-bound tasks): While Node.js is single-threaded for I/O
tasks, it allows for offloading CPU-intensive tasks to worker threads. This helps to
maintain the responsiveness of the event loop while heavy computations are being
handled.
5. Child Processes: Node.js can spawn child processes to handle specific tasks that
might otherwise block the main thread. These child processes run independently and
communicate with the main process via inter-process communication (IPC).

d) How does Node.js handle a file request?

When Node.js handles a file request, it uses its built-in File System (fs) module to perform
the necessary I/O operations. Node.js typically handles file requests asynchronously to avoid
blocking the event loop and ensure other tasks can continue while waiting for the file
operation to complete.

Steps for Handling a File Request:

1. Receive the Request: The server receives an HTTP request (e.g., from a web
browser) asking for a specific file (e.g., an image, HTML page, etc.).
2. Use the fs Module: Node.js calls the fs.readFile() or fs.createReadStream()
method (for asynchronous reading of files) to fetch the file from the disk.
3. Send the Response: Once the file is read, the contents are sent back to the client
through the HTTP response. If the file is large, Node.js can stream it back to the client
using streams, reducing memory consumption.

Example:
const fs = require('fs');
const http = require('http');

const server = http.createServer((req, res) => {


if (req.url === '/file') {
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) {
res.statusCode = 500;
res.end('File not found!');
} else {
res.statusCode = 200;
res.end(data); // Send the file content to the client
}
});
} else {
res.statusCode = 404;
res.end('Page not found');
}
});

server.listen(3000, () => {
console.log('Server is running on port 3000');
});

In this example, when a request for /file is made, Node.js reads the file.txt
asynchronously and sends the contents as a response to the client.
e) Write down the command to create package.json file with an example.

To create a package.json file, which is the configuration file that contains metadata about
the project, dependencies, and scripts, you use the following command:

Command:
npm init

Example:
npm init

This command will prompt you with a series of questions to configure the package.json
file. You can either provide answers or press Enter to accept the default values. After
answering all the questions, a package.json file will be generated.

To skip the prompts and generate the file with default values, you can use the following
command:

npm init -y

This will automatically create a package.json file with default values for the project’s name,
version, description, and other fields.

Example of a package.json file:


{
"name": "my-node-app",
"version": "1.0.0",
"description": "A sample Node.js application",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "Your Name",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}

This file now contains information about the project and its dependencies.

Q-3

a) How to write asynchronous data to a file? Explain with a suitable example.

In Node.js, you can write data to a file asynchronously using the fs.writeFile() or
fs.appendFile() methods from the File System (fs) module. These methods allow the
program to continue executing other code while the file writing operation is happening in the
background.
Example of Writing Asynchronously to a File:
const fs = require('fs');

const data = 'This is some sample data written asynchronously.';

fs.writeFile('example.txt', data, 'utf8', (err) => {


if (err) {
console.log('Error writing file:', err);
} else {
console.log('File has been written successfully!');
}
});

Explanation:

• fs.writeFile(): This method writes the data to the specified file asynchronously. If
the file doesn't exist, it will be created. If the file exists, it will be overwritten.
• The callback function is executed once the writing operation is completed, and any
error during the process is handled by checking the err parameter.

This ensures that the program doesn’t block and continues running while the file is being
written.

b) Write a program which uses addListener() method of EventEmitter class.

The EventEmitter class is part of Node.js' events module. You can use the addListener()
method to attach a listener function to an event.

Example of addListener() with EventEmitter:


const EventEmitter = require('events');

// Create an instance of EventEmitter


const myEmitter = new EventEmitter();

// Add a listener to the 'greet' event


myEmitter.addListener('greet', () => {
console.log('Hello, Welcome to Node.js!');
});

// Emit the 'greet' event


myEmitter.emit('greet');

Explanation:

• addListener(): This method is used to add a listener function for a specific event (in
this case, greet).
• emit(): This method triggers the event, and all listeners attached to it are executed.
When greet is emitted, it calls the function that logs a message.

This demonstrates basic event handling in Node.js.


c) Write a short note on NPM.

NPM (Node Package Manager) is the default package manager for Node.js, widely used for
managing libraries and dependencies in Node.js applications. NPM provides a huge
repository of open-source libraries that can be easily installed, updated, and managed through
simple command-line commands.

Key Features of NPM:

1. Package Management: Allows you to install and manage libraries (dependencies)


that your project needs.
2. Version Management: It handles versions of packages, ensuring compatibility by
specifying the version of each dependency in the package.json file.
3. NPM Scripts: You can define and execute custom scripts, such as build processes or
testing commands, in the package.json file.
4. Global and Local Installations: NPM allows you to install packages both globally
(for system-wide use) or locally (specific to the project).
5. NPM Registry: The NPM registry is a massive online collection of open-source
Node.js packages that are freely available for use.

Example:

npm install express # Installs the 'express' package locally


npm install -g nodemon # Installs 'nodemon' globally

d) Write a code for selecting all records from Player's table.

To query a database and retrieve all records from the Player table, we typically use a
database library like mysql2 or mysql in Node.js.

Example using mysql2 package:


const mysql = require('mysql2');

// Create a connection to the database


const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'sports_db'
});

// Query to select all records from the Player's table


connection.query('SELECT * FROM players', (err, results) => {
if (err) {
console.error('Error fetching data:', err);
return;
}
console.log('Player Records:', results);
});
// Close the connection
connection.end();

Explanation:

• mysql.createConnection(): Establishes a connection to the MySQL database.


• connection.query(): Executes the query to select all records from the players
table. The results are returned in the results array.
• connection.end(): Closes the database connection once the query is complete.

e) Explain module.exports in Node.js.

In Node.js, each file is treated as a separate module, and module.exports is used to export
functions, objects, or variables from a module, making them available for import into other
files using require().

Key Concepts:

• module.exports allows you to define what will be accessible from a module when it
is imported by other modules.
• This helps to encapsulate logic within a module and provides a clean API for other
parts of the application to use.

Example:
// math.js (module file)
module.exports.add = function (a, b) {
return a + b;
};

module.exports.subtract = function (a, b) {


return a - b;
};
// app.js (file importing the module)
const math = require('./math');

console.log(math.add(5, 3)); // Output: 8


console.log(math.subtract(5, 3)); // Output: 2

Explanation:

• module.exports.add and module.exports.subtract: The add and subtract


functions are exported from the math.js module.
• require('./math'): In app.js, the math module is imported, and its functions are
used in the application.

By using module.exports, you can effectively structure your Node.js application by


splitting code into reusable modules.
Q-4

a) Compare Traditional Web Server Model and Node.js Process Model.

The traditional web server model and the Node.js process model differ significantly in how
they handle client requests and manage resources.

Traditional Web Server Model:

1. Multi-threading: In traditional web servers (e.g., Apache, IIS), each incoming


request typically results in the creation of a new thread or process. Each thread
handles a single request, and multiple threads run concurrently to handle multiple
requests.
2. Blocking I/O: Traditional web servers tend to block the thread while waiting for I/O
operations (e.g., reading from disk, querying a database). This means that each thread
is occupied while waiting for I/O operations, leading to inefficient resource usage.
3. Resource Intensive: Since each request requires a separate thread or process,
traditional servers may face performance degradation under high loads due to the
overhead of managing multiple threads.
4. Scalability: Traditional web servers may require load balancing and scaling
horizontally (adding more servers) to handle increased traffic effectively.

Node.js Process Model:

1. Single-Threaded: Node.js operates on a single-threaded, event-driven architecture. It


processes multiple client requests in a non-blocking, asynchronous manner, using a
single thread.
2. Non-blocking I/O: Node.js uses non-blocking I/O operations, meaning it doesn't wait
for I/O operations to finish before moving to the next task. This allows Node.js to
handle many requests concurrently without blocking the execution of other
operations.
3. Event-Driven: Node.js relies on the event loop to handle asynchronous operations.
When an I/O operation is requested, Node.js registers a callback and continues
processing other tasks. Once the I/O operation is complete, the callback is invoked.
4. Lightweight: Node.js can handle thousands of concurrent connections with minimal
overhead, making it lightweight and efficient for handling real-time applications and
high concurrency.

Key Differences:

• Concurrency: Traditional servers rely on multiple threads, while Node.js uses a


single-threaded event loop.
• Performance: Node.js is more efficient for I/O-heavy operations due to its non-
blocking nature, while traditional servers may experience bottlenecks due to blocking
I/O.
• Resource Usage: Node.js is more resource-efficient since it doesn’t need to create
multiple threads for each request.
b) Write a Node.js application to create a user-defined square module to find the area of
a square & display the details on the console.

Application Example:

square.js (user-defined module to calculate the area of a square):

// square.js (Square module)


module.exports.area = function(sideLength) {
return sideLength * sideLength;
};

app.js (main file to use the square module):

// app.js
const square = require('./square');

const sideLength = 5;
const area = square.area(sideLength);

console.log(`The side length of the square is: ${sideLength}`);


console.log(`The area of the square is: ${area}`);

Explanation:

• square.js: This module exports a function area() that takes the side length of a
square and calculates its area by squaring the side length.
• app.js: This file imports the square module using require() and calls the area()
function with a specified side length, logging the results to the console.

c) What is a Web Server?

A web server is a software or hardware system that serves HTTP requests by delivering web
pages, files, and data to clients (usually web browsers). It listens for incoming requests from
users (clients) over the internet, processes these requests, and sends the appropriate response
(such as HTML pages, images, or data) back to the client.

Key Functions of a Web Server:

1. Handling HTTP Requests: Web servers handle requests made via the HTTP/HTTPS
protocol from clients (browsers).
2. Serving Static and Dynamic Content: They serve static files (like HTML, CSS,
JavaScript, images) and dynamic content generated by server-side applications.
3. Routing Requests: Web servers can route requests to appropriate application code
(like Node.js, PHP, or ASP.NET) for processing and generation of dynamic content.

Common Web Servers:

• Apache HTTP Server


• NGINX
• IIS (Internet Information Services)
• Node.js with Express

d) Write a program to create a file in Node.js.

In Node.js, you can use the fs module to create and write data to a file.

Example Program to Create a File:


const fs = require('fs');

// Data to write into the file


const content = 'Hello, this is a test file created using Node.js!';

// Create and write to the file asynchronously


fs.writeFile('testFile.txt', content, 'utf8', (err) => {
if (err) {
console.log('Error writing to file:', err);
} else {
console.log('File created successfully!');
}
});

Explanation:

• fs.writeFile(): This function is used to create a file. If the file already exists, it will
overwrite it. If the file doesn’t exist, it will create it and write the provided content
into it.
• The third parameter specifies the encoding (utf8 in this case).
• The callback function checks for errors and confirms the file creation.

e) Explain the parameters of createConnection in Node.js (for MySQL).

In Node.js, the mysql module provides the createConnection() method to establish a


connection to a MySQL database. The method takes an object as its argument, containing the
configuration parameters for the connection.

Parameters of createConnection():

1. host (string): The hostname of the MySQL server (e.g., 'localhost' or an IP


address).
2. user (string): The username to authenticate with the MySQL server (e.g., 'root').
3. password (string): The password associated with the MySQL user.
4. database (string): The name of the database to connect to.
5. port (number, optional): The port on which MySQL is listening. Default is 3306.
6. socketPath (string, optional): The UNIX socket path to use for the connection.
7. timezone (string, optional): The timezone for the connection (e.g., 'Z' for UTC).

Example:
const mysql = require('mysql');

// Create a connection to the MySQL database


const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password123',
database: 'my_database',
port: 3306
});

// Connect to the database


connection.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err.stack);
return;
}
console.log('Connected to the database as ID ' + connection.threadId);
});

// Close the connection


connection.end();

Explanation:

• createConnection(): Establishes a connection to the specified MySQL database using


the provided credentials and configurations.
• connection.connect(): This method initiates the connection and handles any errors
that might occur during the connection process.
• connection.end(): Closes the database connection after the operations are complete.

This setup allows you to interact with a MySQL database from your Node.js application.

Q-5

a) Explain Event-Driven Programming.

Event-driven programming is a programming paradigm in which the flow of the program is


determined by events or user actions, such as mouse clicks, keyboard input, or messages from
other programs. In this model, the program typically waits for an event to occur and then
responds to it by executing a corresponding function or callback.

Key Concepts:

1. Events: Events represent actions or occurrences that happen, such as user interactions
(click, input) or system-generated signals (e.g., file completion, server request).
2. Event Loop: In event-driven programming, an event loop continuously waits for
events to occur. Once an event is detected, the program triggers the corresponding
callback function to handle the event.
3. Callback Functions: These are functions that are passed as arguments to other
functions and are executed when a certain event occurs.
4. Non-blocking Nature: In event-driven systems like Node.js, I/O operations are
handled asynchronously. The program continues executing other tasks while waiting
for an event to complete.

Example:

In Node.js, the event-driven model is implemented using the EventEmitter class:

const EventEmitter = require('events');


const eventEmitter = new EventEmitter();

eventEmitter.on('greet', () => {
console.log('Hello, Event-Driven Programming!');
});

eventEmitter.emit('greet');

Explanation:

• The program listens for the greet event and responds by executing the callback
function that logs a message to the console.

b) What is an Anonymous Function?

An anonymous function is a function that is defined without a name. These functions are
typically used as arguments to other functions or executed immediately.

Key Features:

1. No Name: Unlike traditional functions, an anonymous function does not have a name.
2. Usage: Anonymous functions are often passed as callbacks or arguments to higher-
order functions.
3. Short-lived: They are usually invoked at the point where they are defined, which
makes them ideal for one-time use or as callback functions.

Example:
// Using an anonymous function as a callback
setTimeout(function() {
console.log('This is an anonymous function!');
}, 1000);

Alternatively, arrow functions are a more concise way to write anonymous functions:

setTimeout(() => {
console.log('This is an anonymous arrow function!');
}, 1000);
Explanation:

• In both cases, the function doesn't have a name and is used directly within the context
where it is needed (as a callback function in setTimeout).

c) Explain Module.

In Node.js, a module is a file or a collection of files that contains code encapsulated in a


specific unit of functionality. Modules help in organizing and structuring the code in a
reusable manner, allowing different parts of the application to communicate and interact with
each other.

Key Concepts:

1. Encapsulation: Modules allow you to bundle code into separate units, making it
easier to manage and maintain.
2. Exports: In Node.js, module.exports is used to expose functionality (like functions,
variables, or objects) from a module so that it can be used in other modules via
require().
3. Built-in and Custom Modules: Node.js provides a set of core modules (like fs,
http, path), and you can create your own custom modules as needed.

Example of a Custom Module:

math.js (Custom module):

module.exports.add = function(a, b) {
return a + b;
};

module.exports.subtract = function(a, b) {
return a - b;
};

app.js (Using the custom module):

const math = require('./math');


console.log(math.add(5, 3)); // Output: 8
console.log(math.subtract(5, 3)); // Output: 2

Explanation:

• module.exports is used to export the functions add and subtract from the math.js
module.
• In app.js, the math module is imported using require('./math'), and its functions
are used.
Node.js modules help to break down large applications into smaller, manageable pieces that
can be reused across different parts of the application.

NODEJS PAPER-3

Q-1

a) What is REPL in Node.js?

REPL stands for Read-Eval-Print-Loop, and it is an interactive shell in Node.js that allows
developers to execute JavaScript code in a command-line environment. It reads user input,
evaluates the expression, prints the result, and then loops back to read the next expression.

Key Features:

• Read: Reads the user input (JavaScript code).


• Eval: Evaluates the JavaScript expression.
• Print: Prints the result to the console.
• Loop: Repeats the process.

Example:

$ node
> console.log("Hello, Node.js!");
Hello, Node.js!

b) NPM stands for?

NPM stands for Node Package Manager. It is the default package manager for Node.js,
used to install, update, and manage JavaScript libraries and dependencies in Node.js
applications.

Key Functions:

• Installing packages from the NPM registry.


• Managing project dependencies in the package.json file.
• Running scripts defined in the package.json file.

c) What do you mean by event in Node.js?

An event in Node.js refers to an action or occurrence (such as a user interaction or a system-


generated signal) that the program can respond to. Node.js uses the EventEmitter class to
handle and emit events.
Key Concepts:

• EventEmitter: A class that allows objects to emit events and handle them using
listeners.
• Event Loop: Node.js uses an event-driven, non-blocking model where events are
handled asynchronously.

Example:

const EventEmitter = require('events');


const emitter = new EventEmitter();
emitter.on('greet', () => console.log('Hello, Event!'));
emitter.emit('greet');

d) What is the use of prompt-sync module?

The prompt-sync module in Node.js allows you to synchronously read input from the user
via the command line. It is useful for interactive command-line applications where you need
to ask the user for input and process it synchronously.

Example:
const prompt = require('prompt-sync')();
const name = prompt('What is your name? ');
console.log(`Hello, ${name}!`);

e) Define Anonymous Function.

An anonymous function is a function that is defined without a name. It is often used as a


callback or passed as an argument to another function.

Example:
setTimeout(function() {
console.log("Hello from an anonymous function!");
}, 1000);

Alternatively, arrow functions are a more concise way to write anonymous functions:

setTimeout(() => {
console.log("Hello from an anonymous arrow function!");
}, 1000);

f) Explain global packages from Node.js.

Global packages in Node.js are installed system-wide, meaning they can be used in any
project or command-line application without needing to install them locally. These packages
are useful for tools or utilities that you use across multiple projects.
Example:
npm install -g nodemon # Installs nodemon globally

Global packages are installed using the -g flag and can be used directly in the terminal.

g) What is Express.js?

Express.js is a fast, unopinionated, and minimal web application framework for Node.js. It
simplifies the process of building web applications and APIs by providing a set of tools for
routing, middleware, and handling HTTP requests.

Key Features:

• Simplifies HTTP request handling with a robust set of features.


• Middleware support for adding custom processing on requests and responses.
• Routing system to define how different HTTP requests should be handled.

h) Write syntax to create Buffer.

A Buffer in Node.js is a raw memory allocation used to handle binary data. It is particularly
useful for dealing with streams and working with file I/O.

Syntax:
const buffer = Buffer.from('Hello, Node.js!');
console.log(buffer);

You can also create a buffer with a specified size:

const buffer = Buffer.alloc(10); // Allocates a buffer of size 10 bytes

i) Which command is used for deleting a file?

In Node.js, the fs module provides methods for interacting with the file system. To delete a
file, use fs.unlink() or fs.unlinkSync().

Example:
const fs = require('fs');

fs.unlink('file-to-delete.txt', (err) => {


if (err) {
console.log('Error deleting file:', err);
} else {
console.log('File deleted successfully');
}
});

Alternatively, use the synchronous version:

fs.unlinkSync('file-to-delete.txt');

Q-2

a) What is Node.js? Explain the features of Node.js.

Node.js is a powerful, open-source, cross-platform runtime environment built on Chrome's


V8 JavaScript engine. It allows developers to run JavaScript code outside the browser,
enabling the development of scalable and efficient server-side applications. Node.js is
particularly well-suited for building applications that require real-time data, high
concurrency, and fast I/O operations, such as chat applications, real-time collaboration tools,
and APIs.

Key Features of Node.js:

1. Asynchronous and Non-blocking I/O:


o Node.js uses non-blocking, asynchronous I/O operations, meaning it doesn't
wait for I/O tasks (like file reading or database queries) to complete before
moving to the next task. This allows Node.js to handle many tasks
concurrently, making it ideal for scalable, high-performance applications.
2. Single-Threaded Event Loop:
o Node.js operates on a single-threaded event loop, which processes multiple
requests without creating multiple threads. This reduces memory usage and
allows it to handle a large number of simultaneous connections with low
overhead.
3. Fast Execution with V8 Engine:
o Node.js is built on Chrome’s V8 JavaScript engine, which compiles JavaScript
into machine code, providing high performance and fast execution of
JavaScript code.
4. Cross-Platform:
o Node.js is platform-agnostic, meaning it can run on various operating systems,
including Linux, macOS, and Windows, making it a versatile choice for cross-
platform applications.
5. Scalability:
o The event-driven architecture of Node.js allows it to scale easily with more
resources and load. It is suitable for building both small applications and
large-scale systems that require high scalability.
6. Rich Ecosystem with NPM:
o Node.js has a vibrant ecosystem, thanks to the Node Package Manager (NPM).
With over a million packages available, developers can easily integrate third-
party libraries and tools into their applications.
7. Real-Time Capabilities:
o Node.js is particularly strong in real-time applications like chat applications,
online gaming, and live updates, thanks to its asynchronous nature and support
for WebSockets.
b) How we can create a local module with an example?

In Node.js, you can create a local module by creating a JavaScript file and exporting
functions, objects, or variables using module.exports. The module can then be imported and
used in other parts of your application using require().

Steps to Create a Local Module:

1. Create the module file: This file will define the functionality you want to export.
2. Export the functionality: Use module.exports to export the functions or variables.
3. Require the module in another file: Use require() to import and use the module in
other files.

Example:

math.js (Local Module):

// math.js
module.exports.add = function(a, b) {
return a + b;
};

module.exports.subtract = function(a, b) {
return a - b;
};

app.js (Main Application):

// app.js
const math = require('./math'); // Import the math.js module

const result1 = math.add(5, 3);


console.log(`Addition result: ${result1}`); // Output: Addition result: 8

const result2 = math.subtract(5, 3);


console.log(`Subtraction result: ${result2}`); // Output: Subtraction
result: 2

Explanation:

• In math.js, the functions add and subtract are exported using module.exports.
• In app.js, the math module is imported using require(), and its functions are used
to perform operations.

c) What is package.json File?


The package.json file is a metadata file in Node.js projects that contains information about
the project, such as its name, version, dependencies, scripts, and more. It is essential for
managing a Node.js project, as it allows NPM to handle dependencies and scripts.

Key Sections of package.json:

1. name: The name of the project or application.


2. version: The current version of the application.
3. scripts: A set of scripts that can be run using the npm run command (e.g., build, test).
4. dependencies: A list of packages that are required to run the application in
production.
5. devDependencies: A list of packages that are needed only during development (e.g.,
testing tools).
6. main: The entry point file of the project (e.g., index.js).
7. author: The author of the application.
8. license: The licensing information for the project.

Example of a package.json file:


{
"name": "my-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "mocha"
},
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"nodemon": "^2.0.7"
},
"author": "Your Name",
"license": "MIT"
}

Explanation:

• The package.json file contains metadata and configuration for the project, such as
dependencies, scripts, and project information.
• Running npm install will install the dependencies listed in the dependencies
section.

d) Explain Node.js Process Model?

The Node.js Process Model refers to how Node.js handles processes to execute code,
specifically focusing on the event-driven, non-blocking, and single-threaded nature of
Node.js.
Key Points of the Node.js Process Model:

1. Single-Threaded Event Loop:


o Node.js runs on a single thread, handling requests through an event loop. It
doesn't create new threads for each request. Instead, it uses an event-driven
architecture that allows it to handle multiple requests concurrently without
blocking the execution.
2. Event-Driven:
o The core of Node.js is its event loop, which listens for events and triggers
appropriate callbacks. This makes it highly efficient for I/O-heavy tasks, as it
doesn't wait for an operation to complete before moving on to the next.
3. Non-blocking I/O:
o In Node.js, I/O operations such as reading files or querying a database are
handled asynchronously. When an I/O task is requested, Node.js delegates it to
the system and continues executing other code. Once the I/O task is complete,
it triggers a callback function to handle the result.
4. Scalable and Lightweight:
o Because of its non-blocking nature and event-driven model, Node.js can
handle a large number of concurrent requests without consuming significant
system resources. It is ideal for building scalable, high-performance
applications.

e) Write down Advantages of NPM.

The Node Package Manager (NPM) is a vital tool for managing packages and dependencies
in Node.js projects. It provides several advantages for developers.

Advantages of NPM:

1. Easy Dependency Management:


o NPM helps manage project dependencies by automatically downloading and
installing required libraries and tools. It ensures that all dependencies are up to
date and compatible with the project.
2. Access to a Vast Ecosystem:
o NPM provides access to the world's largest collection of open-source
JavaScript libraries, which can be easily installed and used in projects.
3. Package Versioning:
o NPM allows you to specify versions of dependencies, ensuring that your
project uses specific versions that are compatible and stable. It also supports
version ranges and lock files to maintain consistency across environments.
4. Automated Scripts:
o NPM allows you to define custom scripts (e.g., build, test, start) in the
package.json file, which can be run with a simple npm run <script>
command. This streamlines development tasks and automates repetitive
processes.
5. Global and Local Packages:
o
NPM enables you to install packages globally (for use across all projects) or
locally (specific to a single project), giving you flexibility in how you manage
your dependencies.
6. Community Support:
o NPM has a large and active community of developers contributing packages,
plugins, and tools, making it a rich ecosystem for Node.js development.

Q-3

a) Explain module.exports in Node.js?

In Node.js, module.exports is an object that is used to export functions, objects, or variables


from a module so that they can be imported and used in other files. By default, each module
in Node.js has a module.exports object, which you can modify to export a specific function
or set of functions.

How It Works:

• You define your logic inside a module (a JavaScript file).


• Then, you use module.exports to expose the functionality (functions, objects, or
variables) that you want to use in other files.
• You can then import that module using the require() function in other parts of your
application.

Example:

math.js (Module that exports functionality)

// math.js
module.exports.add = function(a, b) {
return a + b;
};

module.exports.subtract = function(a, b) {
return a - b;
};

app.js (Importing and using the exported module)

// app.js
const math = require('./math'); // Import the math.js module

const sum = math.add(5, 3);


console.log(`Sum: ${sum}`); // Output: Sum: 8

const difference = math.subtract(5, 3);


console.log(`Difference: ${difference}`); // Output: Difference: 2

In this example, module.exports allows the add and subtract functions to be available for
use in the app.js file.
b) Write steps to load core modules in Node.js?

In Node.js, core modules are built-in modules that are readily available to use without
requiring installation. These modules provide basic functionality like file system handling,
networking, and more.

Steps to Load Core Modules in Node.js:

1. Identify the Core Module:


o Core modules are bundled with Node.js, such as fs, http, path, etc.
2. Use require() to Load the Module:
o To use a core module, you simply require it by passing its name as a string to
the require() function.

Example:
// Loading core modules
const fs = require('fs'); // File System module
const http = require('http'); // HTTP module
const path = require('path'); // Path module

// Example usage of fs module


fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});

In this example, we load the fs, http, and path core modules using require() and use them
for file operations, web server handling, and path operations.

c) How to write synchronous data to a file? Explain with a suitable example.

In Node.js, you can use the fs module to write data to a file. For synchronous file writing, the
fs.writeFileSync() method is used. This method writes data to a file in a blocking
(synchronous) manner, meaning the program will wait for the file operation to complete
before continuing execution.

Syntax:
fs.writeFileSync(path, data, options);

• path: The path to the file where data will be written.


• data: The data to be written to the file.
• options: (Optional) The encoding or flags (default is 'utf8').

Example:
const fs = require('fs');
const data = 'This is some text data that will be written to a file.';

// Writing data to file synchronously


fs.writeFileSync('example.txt', data);

console.log('Data written to file successfully!');

Explanation:

• The fs.writeFileSync() method writes the specified data (data) to the file
example.txt synchronously. The program will not proceed to the next line until the
file has been written.

d) Write a code for selecting all records from the “employee” table.

To select all records from the "employee" table in a database, you would typically use a
database query with an SQL SELECT statement. In Node.js, you can interact with MySQL
using the mysql module.

Example (Using MySQL with Node.js):

First, ensure you have installed the mysql package using NPM:

npm install mysql

Now, you can write the code to select all records from the "employee" table.

const mysql = require('mysql');

// Create a connection to the database


const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'company_db'
});

// Connect to the database


connection.connect((err) => {
if (err) {
console.error('Error connecting to the database: ' + err.stack);
return;
}
console.log('Connected to the database');
});

// Query to select all records from the employee table


connection.query('SELECT * FROM employee', (err, results, fields) => {
if (err) throw err;
console.log('Employee Records:', results);
});
// Close the connection
connection.end();

Explanation:

• We use the mysql.createConnection() method to set up the connection to the


database.
• The connection.query() method is used to run an SQL SELECT query to fetch all
records from the employee table.
• The results are returned in the results parameter and logged to the console.

e) Using Node.js, create a webpage to read two file names from the user and combine
them into a third file.

This task involves creating a simple web server in Node.js using the express module to
interact with the user, read file names, and combine the files. The fs module will be used to
read and write files.

Steps:

1. Install the required modules:


2. npm install express
3. Create the webpage and the logic to combine the files.

Example Code:

server.js (Node.js Server File):

const express = require('express');


const fs = require('fs');
const path = require('path');
const app = express();
const port = 3000;

// Middleware to parse form data


app.use(express.urlencoded({ extended: true }));

// Serve the HTML form


app.get('/', (req, res) => {
res.send(`
<form action="/combine" method="post">
<label for="file1">Enter the first file name: </label>
<input type="text" id="file1" name="file1" required><br><br>
<label for="file2">Enter the second file name: </label>
<input type="text" id="file2" name="file2" required><br><br>
<button type="submit">Combine Files</button>
</form>
`);
});

// Route to handle the file combination


app.post('/combine', (req, res) => {
const { file1, file2 } = req.body;

// Read the content of both files


const filePath1 = path.join(__dirname, file1);
const filePath2 = path.join(__dirname, file2);

fs.readFile(filePath1, 'utf8', (err, data1) => {


if (err) return res.send('Error reading first file: ' + err.message);

fs.readFile(filePath2, 'utf8', (err, data2) => {


if (err) return res.send('Error reading second file: ' +
err.message);

// Combine the contents of both files


const combinedData = data1 + '\n' + data2;

// Write the combined data to a third file


fs.writeFile('combined.txt', combinedData, (err) => {
if (err) return res.send('Error writing combined file: ' +
err.message);
res.send('Files combined successfully! <a
href="/combined.txt">Download the combined file</a>');
});
});
});
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});

Explanation:

• We set up an Express server to serve an HTML form where the user can input the
names of two files.
• On form submission, the server reads the content of the two files, combines the data,
and writes it to a new file called combined.txt.
• The user is given a link to download the combined file once the process is complete.

Run this server with node server.js, and you can access it at http://localhost:3000.

Q-4

a) Write down the difference between GET and http.request() method?

Feature GET Method http.request() Method

The GET method is used to http.request() is a general method used


Purpose send a request to a server to to send HTTP requests to the server,
retrieve data. including GET, POST, PUT, etc.
Feature GET Method http.request() Method

It is used specifically for It is a more generic method used to handle


Usage making HTTP GET requests to all types of HTTP requests (GET, POST, PUT,
fetch data from the server. DELETE, etc.).

A type of HTTP request


Method A low-level method that can be used to
method (GET) used to fetch
Type make custom HTTP requests.
data.

Syntax http.get(url, callback) http.request(options, callback)

It is a simplified version of More flexible, allows you to specify various


Simplified http.request() for GET options like HTTP headers, method type
requests. (GET, POST), etc.

Example:
// Using GET method
const http = require('http');
http.get('http://example.com', (res) => {
let data = '';
res.on('data', chunk => { data += chunk; });
res.on('end', () => { console.log(data); });
});

// Using http.request() method


const options = {
hostname: 'example.com',
port: 80,
path: '/',
method: 'GET'
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', chunk => { data += chunk; });
res.on('end', () => { console.log(data); });
});
req.end();

b) What is the use of fs.ftruncate() method?

The fs.ftruncate() method in Node.js is used to truncate (shorten or lengthen) a file to a


specified length. It is often used to resize a file. If the specified length is greater than the file
size, the file is extended with zero bytes. If the length is smaller than the file size, the file is
truncated to that length.

Syntax:
fs.ftruncate(fd, len, callback);
• fd: The file descriptor of the file.
• len: The length to which the file should be truncated.
• callback: A function that is called once the truncation operation is completed.

Example:
const fs = require('fs');

fs.open('example.txt', 'r+', (err, fd) => {


if (err) throw err;

// Truncate the file to 5 bytes


fs.ftruncate(fd, 5, (err) => {
if (err) throw err;
console.log('File truncated to 5 bytes.');
});
});

Explanation:

• This example opens the file example.txt in read/write mode, then truncates it to 5
bytes.

c) Write a Node.js application to create a user-defined Rectangle module to find the


area of the rectangle & display the details on the console.

Steps:

1. Create a rectangle.js module to define the Rectangle class and calculate the area.
2. Import and use this module in the main file (app.js).

rectangle.js (Rectangle Module):


// rectangle.js
class Rectangle {
constructor(length, width) {
this.length = length;
this.width = width;
}

// Method to calculate area of the rectangle


area() {
return this.length * this.width;
}

// Method to display details


display() {
console.log(`Length: ${this.length}, Width: ${this.width}`);
console.log(`Area: ${this.area()}`);
}
}

module.exports = Rectangle;
app.js (Main File):
// app.js
const Rectangle = require('./rectangle'); // Import the rectangle module

// Create an instance of Rectangle


const rect = new Rectangle(10, 5);

// Display the details and area of the rectangle


rect.display();

Output:
Length: 10, Width: 5
Area: 50

Explanation:

• The Rectangle class in rectangle.js contains methods to calculate the area and
display the details of the rectangle.
• The main file imports the Rectangle class, creates an instance, and calls the methods
to display the area and details.

d) What is a web server?

A web server is a software system that serves content (such as web pages, images, etc.) to
clients over the internet. It listens for incoming HTTP requests from clients (usually
browsers) and returns the requested content, such as HTML files, images, or other data.

Functions of a Web Server:

1. HTTP Request Handling: A web server listens for HTTP requests, processes them,
and sends appropriate responses.
2. Serving Static Content: It can serve static files (e.g., HTML, CSS, JavaScript) stored
on the server.
3. Dynamic Content: Web servers can work with server-side languages (like Node.js,
PHP, or Python) to dynamically generate and serve content.
4. Security and Authentication: It may implement security protocols like SSL/TLS for
encrypted communication.

Popular Web Servers:

• Apache HTTP Server


• Nginx
• Microsoft IIS
• Node.js (used for building custom web servers)
e) Explain parameters of createConnection?

The mysql.createConnection() method in Node.js is used to create a connection to a


MySQL database. This method accepts an object as a parameter, containing the necessary
information to establish a connection.

Syntax:
const connection = mysql.createConnection({
host: 'localhost', // Database host
user: 'root', // Username
password: 'password', // Password for the user
database: 'mydb', // Name of the database to connect to
port: 3306 // (Optional) Port number (default is 3306)
});

Parameters:

1. host: The hostname or IP address of the MySQL server.


2. user: The MySQL username that has access to the database.
3. password: The password associated with the MySQL user.
4. database: The name of the database to connect to.
5. port (Optional): The port number of the MySQL server (default is 3306).
6. socketPath (Optional): The UNIX socket file path, for connecting to a MySQL server
via a socket.

Example:
const mysql = require('mysql');

const connection = mysql.createConnection({


host: 'localhost',
user: 'root',
password: 'password',
database: 'company_db'
});

connection.connect((err) => {
if (err) throw err;
console.log('Connected to the database');
});

Explanation:

• This example demonstrates creating a MySQL connection using


mysql.createConnection(), passing the necessary connection parameters to access
a company_db database.

Q-5

a) Explain path module.


The path module in Node.js is a built-in module used for handling and working with file and
directory paths. It provides utility methods to manipulate paths in a way that works across
different operating systems, ensuring that the correct path format (e.g., forward slashes on
Unix-based systems, backslashes on Windows) is used.

Key Methods of the path Module:

1. path.join([...paths]): Joins all given path segments into a single path. It


normalizes the resulting path.
o Example: path.join('/foo', 'bar', 'baz/asdf', 'quux', '..') will
return '/foo/bar/baz/asdf'.
2. path.resolve([...paths]): Resolves a sequence of paths into an absolute path.
o Example: path.resolve('/foo', 'bar') returns /foo/bar if the first
argument is an absolute path.
3. path.basename(path): Returns the last part of the path (the file or directory name).
o Example: path.basename('/foo/bar/baz/asdf/quux.html') returns
'quux.html'.
4. path.extname(path): Returns the file extension from the given path.
o Example: path.extname('index.html') returns '.html'.
5. path.dirname(path): Returns the directory name of the given path.
o Example: path.dirname('/foo/bar/baz/asdf/quux') returns
/foo/bar/baz/asdf.

Example:
const path = require('path');

// Joining paths
console.log(path.join('foo', 'bar', 'baz/asdf', 'quux', '..')); // Output:
foo/bar/baz/asdf

// Resolving paths
console.log(path.resolve('foo/bar', '/tmp/file/')); // Output: /tmp/file

// Extracting the file extension


console.log(path.extname('index.html')); // Output: .html

Explanation:

• The path module helps manage file system paths in a way that works across different
platforms, ensuring that path handling is consistent and error-free.

b) How to uninstall a local package.

In Node.js, local packages are typically installed in the current project directory under the
node_modules folder. To uninstall a local package, you use the npm uninstall command.
Steps to Uninstall a Local Package:

1. Open the terminal or command prompt.


2. Navigate to the root directory of your Node.js project (where the package.json file is
located).
3. Use the following command to uninstall a specific package:
4. npm uninstall <package_name>

For example:

npm uninstall lodash

5. If you want to remove the package both from node_modules and package.json, you
can add the --save or --save-dev flag (depending on whether it is a regular or
development dependency):
6. npm uninstall <package_name> --save
7. To uninstall multiple packages at once, simply list them:
8. npm uninstall package1 package2

Example:
npm uninstall express

This will remove the express package from the node_modules folder and also update the
package.json file.

Explanation:

• The npm uninstall command removes the specified package from both the
node_modules folder and package.json, ensuring that it is no longer a part of your
project.

c) How can we add a Dependency in package.json.

In Node.js, dependencies are packages or modules that your project needs to function. These
dependencies are added to your project’s package.json file under the dependencies
section. You can add dependencies using the npm install command, which automatically
adds the dependency to your package.json file.

Steps to Add a Dependency:

1. Install a Dependency:
o To add a new dependency, run the following command:
o npm install <package_name>
o For example, to install the express package:
o npm install express
2. Saving the Dependency:
o By default, npm install <package_name> adds the dependency to the
dependencies section of your package.json file.
o If you need to add it as a development dependency (for packages used only
during development like testing frameworks), use the --save-dev flag:
o npm install <package_name> --save-dev
3. Manually Editing package.json:
o You can also manually add a dependency by directly editing the
dependencies section of the package.json file, though using npm install
is recommended as it ensures the correct version and metadata.

Example:
npm install lodash --save

After running this command, your package.json will have the following dependencies
section:

"dependencies": {
"lodash": "^4.17.21"
}

Explanation:

• Running npm install <package_name> automatically adds the specified package to


the dependencies section in package.json, ensuring that the package will be
installed if someone else clones the project and runs npm install.

NODEJS PAPER-4

Q-1

a) What is the Command to initialize Node Package Manager (NPM)? Write its syntax.

To initialize NPM in a Node.js project, the following command is used:

npm init

• Syntax: npm init will interactively guide you through creating a package.json file.
Alternatively, you can use npm init -y to automatically generate the package.json
with default values.

b) What is REPL?

REPL stands for Read-Eval-Print Loop. It is an interactive shell in Node.js that allows
developers to enter JavaScript expressions and get immediate results. The REPL reads the
user's input, evaluates it, prints the result, and loops back to wait for more input.
• Usage: It is used for testing small code snippets and quickly experimenting with
JavaScript.

c) List any four core modules of Node.js.

1. http: Provides utilities to create HTTP servers and handle HTTP requests and
responses.
2. fs: Allows interacting with the file system, including reading, writing, and modifying
files.
3. path: Provides utilities for working with file and directory paths.
4. events: Implements the EventEmitter class, which allows for event-driven
programming.

d) Which directive is used to import Node.js modules?

The require() directive is used to import Node.js modules.

• Syntax: const moduleName = require('module-name');

Example:

const http = require('http');

e) List any 4 methods included under the path module of Node.js.

1. path.join(): Joins multiple path segments into a single normalized path.


2. path.resolve(): Resolves a sequence of paths into an absolute path.
3. path.basename(): Returns the last part of a path (file or directory name).
4. path.extname(): Returns the file extension of a given path.

f) For which tasks is a file system module used?

The fs module in Node.js is used for interacting with the file system, performing tasks such
as:

1. Reading files: fs.readFile(), fs.readFileSync()


2. Writing files: fs.writeFile(), fs.writeFileSync()
3. Modifying files: fs.appendFile()
4. File system operations: Create, rename, delete files and directories.
g) Write a command to add dependency “express” using NPM.

To add the express dependency to your project using NPM, use the following command:

npm install express --save

• Explanation: This command will install express and add it to the dependencies
section of your package.json.

h) Write a command to install MySQL package by using NPM.

To install the mysql package in a Node.js project, use the following command:

npm install mysql --save

• Explanation: This will install the mysql package and add it to the dependencies
section in package.json.

i) In which situation Node.js is not recommended to use?

Node.js is not recommended for:

1. CPU-intensive operations: Node.js runs on a single thread, so tasks like complex


calculations and heavy computations may block the event loop, causing performance
issues.
2. Blocking I/O operations: If your application heavily relies on blocking I/O (e.g., file
reading, database queries), it may not be the best fit for Node.js.

j) Write steps to handle HTTP requests while creating a web server using Node.js.

To handle HTTP requests in Node.js while creating a web server, follow these steps:

1. Import the http module:


2. const http = require('http');
3. Create the server using http.createServer():
4. const server = http.createServer((req, res) => {
5. // Request handling logic
6. });
7. Define the logic to handle incoming requests: In the callback function passed to
createServer, handle request details like req.url, req.method, and provide
responses via the res object.
8. Start the server by calling server.listen():
9. server.listen(3000, () => {
10. console.log('Server is running on port 3000');
11. });

Example:
const http = require('http');

const server = http.createServer((req, res) => {


res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!');
});

server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});

• Explanation: This example creates a basic HTTP server that listens on port 3000 and
responds with "Hello, World!" for every request.

Q-2

a) What are the advantages of Node.js?

Node.js provides several key advantages that make it an ideal choice for building scalable
and efficient applications, especially for web servers and real-time applications. Some of the
main advantages are:

1. Non-blocking, Asynchronous I/O: Node.js uses an event-driven, non-blocking I/O


model, allowing it to handle multiple requests concurrently without waiting for one
operation to complete before starting another. This leads to better performance and
faster response times.
2. Single Programming Language (JavaScript): Node.js allows developers to use
JavaScript on both the client-side and server-side, streamlining development by using
the same language throughout the stack.
3. Scalability: Node.js can handle a large number of simultaneous connections
efficiently, which makes it ideal for building scalable applications, such as chat
applications and live updates.
4. Lightweight and Efficient: The use of the V8 JavaScript engine and non-blocking
I/O makes Node.js lightweight and efficient, which is especially useful for
applications that need high throughput and low latency.
5. Large Ecosystem (NPM): Node.js comes with the Node Package Manager (NPM),
which provides access to a massive repository of open-source libraries and modules
that can speed up development and reduce code complexity.
6. Real-Time Applications: Node.js is well-suited for real-time applications like chat
applications, multiplayer games, and collaborative platforms, thanks to its event-
driven, non-blocking nature.
7. Cross-Platform: Node.js can run on different platforms like Windows, Linux, and
macOS, making it easy to develop and deploy applications on a variety of operating
systems.

b) Write a program to update table records using Node.js and MySQL database.
To update a record in a MySQL database using Node.js, you first need to establish a
connection to the MySQL server, then use SQL queries to modify the records.

Example:
const mysql = require('mysql');

// Create a connection to the database


const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'my_database'
});

// Connect to the database


connection.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err.stack);
return;
}
console.log('Connected to the database');
});

// Update a record in the 'students' table


const updateQuery = 'UPDATE students SET marks = ? WHERE id = ?';
const newMarks = 85;
const studentId = 1;

connection.query(updateQuery, [newMarks, studentId], (err, result) => {


if (err) {
console.error('Error updating record:', err);
} else {
console.log('Record updated successfully:', result);
}
});

// Close the connection


connection.end();

Explanation:

• First, a MySQL connection is created using the mysql.createConnection()


method.
• The UPDATE SQL query is used to modify the record where the student id is 1 and
update the marks field.
• After executing the query, the connection to the database is closed using
connection.end().

c) Explain Node.js process model with the help of a diagram.

The Node.js process model is based on a single-threaded event loop, which is designed to
handle many connections simultaneously in a non-blocking and efficient manner. Node.js
uses the event-driven, non-blocking I/O model to handle requests asynchronously.
Process Model Overview:

1. Single Threaded: Node.js operates on a single main thread, which handles incoming
requests, executes JavaScript code, and returns responses.
2. Event Loop: The event loop is at the core of Node.js’s non-blocking I/O model. It
continuously checks for events or tasks that need to be processed and executes them
asynchronously.
3. Callback Queue: When I/O tasks are completed (e.g., file reading, database queries),
the results are placed in the callback queue, where the event loop processes them.
4. Libuv (Libuv library): Node.js uses the libuv library to handle I/O operations. It
supports asynchronous I/O for file systems, DNS, and TCP sockets.

Diagram:
+-----------------+
| Event Loop | <-- Event-driven & Asynchronous I/O
+-----------------+
|
v
+--------------+
| Callback |
| Queue |
+--------------+
|
v
+----------------+
| Worker Threads| --> (I/O, DB, Network tasks)
+----------------+

Explanation:

• Event Loop: Handles all incoming requests, dispatching them to the callback queue.
• Callback Queue: Stores tasks (callbacks) that are ready to be executed.
• Worker Threads: Used to perform heavy tasks asynchronously without blocking the
main thread.

d) How does Node.js handle a file request?

Node.js handles file requests asynchronously, meaning it doesn’t block the event loop while
waiting for file operations to complete. Here is how it works:

1. Asynchronous file handling: When a request for a file is made (e.g., via
fs.readFile()), Node.js sends the file request to the underlying operating system.
Node.js then continues to process other requests without waiting for the file operation
to finish.
2. Callback mechanism: Once the file operation is completed (reading, writing, etc.), a
callback function is invoked with the result or error. This ensures the system can
continue processing other tasks while waiting for file operations.
3. Non-blocking behavior: Node.js ensures that it does not block the event loop while
performing file operations. When a file operation completes, the event loop resumes
execution by invoking the appropriate callback function.

Example:
const fs = require('fs');

// Non-blocking file read


fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
} else {
console.log('File contents:', data);
}
});

Explanation:

• fs.readFile() reads the file asynchronously and processes it via a callback function
when the operation completes.

e) What is the purpose of the module.exports in Node.js?

In Node.js, module.exports is used to export functions, objects, or variables from a module


so that they can be required and used in other files.

• Purpose: It allows developers to encapsulate code in modules and share specific parts
of it across different files.
• Syntax: By assigning a value to module.exports, you expose that value to other
modules.

Example:

In math.js:

module.exports.add = function(a, b) {
return a + b;
};

In app.js:

const math = require('./math');


console.log(math.add(2, 3)); // Output: 5

Explanation:

• The add function is exported from math.js and can be used in app.js by requiring
the module.
• module.exports makes functions or objects accessible to other files, enabling
modular programming in Node.js.

Q-3

a) What are the advantages of Node.js?

Node.js provides several key advantages that make it an ideal choice for building scalable
and efficient applications, especially for web servers and real-time applications. Some of the
main advantages are:

1. Non-blocking, Asynchronous I/O: Node.js uses an event-driven, non-blocking I/O


model, allowing it to handle multiple requests concurrently without waiting for one
operation to complete before starting another. This leads to better performance and
faster response times.
2. Single Programming Language (JavaScript): Node.js allows developers to use
JavaScript on both the client-side and server-side, streamlining development by using
the same language throughout the stack.
3. Scalability: Node.js can handle a large number of simultaneous connections
efficiently, which makes it ideal for building scalable applications, such as chat
applications and live updates.
4. Lightweight and Efficient: The use of the V8 JavaScript engine and non-blocking
I/O makes Node.js lightweight and efficient, which is especially useful for
applications that need high throughput and low latency.
5. Large Ecosystem (NPM): Node.js comes with the Node Package Manager (NPM),
which provides access to a massive repository of open-source libraries and modules
that can speed up development and reduce code complexity.
6. Real-Time Applications: Node.js is well-suited for real-time applications like chat
applications, multiplayer games, and collaborative platforms, thanks to its event-
driven, non-blocking nature.
7. Cross-Platform: Node.js can run on different platforms like Windows, Linux, and
macOS, making it easy to develop and deploy applications on a variety of operating
systems.

b) Write a program to update table records using Node.js and MySQL database.

To update a record in a MySQL database using Node.js, you first need to establish a
connection to the MySQL server, then use SQL queries to modify the records.

Example:
const mysql = require('mysql');

// Create a connection to the database


const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'my_database'
});

// Connect to the database


connection.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err.stack);
return;
}
console.log('Connected to the database');
});

// Update a record in the 'students' table


const updateQuery = 'UPDATE students SET marks = ? WHERE id = ?';
const newMarks = 85;
const studentId = 1;

connection.query(updateQuery, [newMarks, studentId], (err, result) => {


if (err) {
console.error('Error updating record:', err);
} else {
console.log('Record updated successfully:', result);
}
});

// Close the connection


connection.end();

Explanation:

• First, a MySQL connection is created using the mysql.createConnection()


method.
• The UPDATE SQL query is used to modify the record where the student id is 1 and
update the marks field.
• After executing the query, the connection to the database is closed using
connection.end().

c) Explain Node.js process model with the help of a diagram.

The Node.js process model is based on a single-threaded event loop, which is designed to
handle many connections simultaneously in a non-blocking and efficient manner. Node.js
uses the event-driven, non-blocking I/O model to handle requests asynchronously.

Process Model Overview:

1. Single Threaded: Node.js operates on a single main thread, which handles incoming
requests, executes JavaScript code, and returns responses.
2. Event Loop: The event loop is at the core of Node.js’s non-blocking I/O model. It
continuously checks for events or tasks that need to be processed and executes them
asynchronously.
3. Callback Queue: When I/O tasks are completed (e.g., file reading, database queries),
the results are placed in the callback queue, where the event loop processes them.
4. Libuv (Libuv library): Node.js uses the libuv library to handle I/O operations. It
supports asynchronous I/O for file systems, DNS, and TCP sockets.

Diagram:
+-----------------+
| Event Loop | <-- Event-driven & Asynchronous I/O
+-----------------+
|
v
+--------------+
| Callback |
| Queue |
+--------------+
|
v
+----------------+
| Worker Threads| --> (I/O, DB, Network tasks)
+----------------+

Explanation:

• Event Loop: Handles all incoming requests, dispatching them to the callback queue.
• Callback Queue: Stores tasks (callbacks) that are ready to be executed.
• Worker Threads: Used to perform heavy tasks asynchronously without blocking the
main thread.

d) How does Node.js handle a file request?

Node.js handles file requests asynchronously, meaning it doesn’t block the event loop while
waiting for file operations to complete. Here is how it works:

1. Asynchronous file handling: When a request for a file is made (e.g., via
fs.readFile()), Node.js sends the file request to the underlying operating system.
Node.js then continues to process other requests without waiting for the file operation
to finish.
2. Callback mechanism: Once the file operation is completed (reading, writing, etc.), a
callback function is invoked with the result or error. This ensures the system can
continue processing other tasks while waiting for file operations.
3. Non-blocking behavior: Node.js ensures that it does not block the event loop while
performing file operations. When a file operation completes, the event loop resumes
execution by invoking the appropriate callback function.

Example:
const fs = require('fs');

// Non-blocking file read


fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
} else {
console.log('File contents:', data);
}
});

Explanation:

• fs.readFile() reads the file asynchronously and processes it via a callback function
when the operation completes.

e) What is the purpose of the module.exports in Node.js?

In Node.js, module.exports is used to export functions, objects, or variables from a module


so that they can be required and used in other files.

• Purpose: It allows developers to encapsulate code in modules and share specific parts
of it across different files.
• Syntax: By assigning a value to module.exports, you expose that value to other
modules.

Example:

In math.js:

module.exports.add = function(a, b) {
return a + b;
};

In app.js:

const math = require('./math');


console.log(math.add(2, 3)); // Output: 5

Explanation:

• The add function is exported from math.js and can be used in app.js by requiring
the module.
• module.exports makes functions or objects accessible to other files, enabling
modular programming in Node.js.

Q-4

a) What are different features of Node.js?

• Asynchronous and Event-driven: Node.js uses non-blocking I/O, meaning it can


handle many operations simultaneously without waiting.
• Single-threaded but scalable: Uses a single-threaded event loop architecture,
allowing it to handle thousands of concurrent connections.
• Very Fast: Built on Google Chrome's V8 JavaScript engine, offering high
performance.
• No Buffering: Processes data in chunks, so no buffering of data while uploading.
• Cross-platform: Runs on Windows, Linux, Unix, macOS, etc.
• NPM (Node Package Manager): Comes with thousands of libraries to enhance
functionality.

b) Compare Traditional Web Server Model and Node.js Process Model

Traditional Web Server Node.js Process Model

Uses multi-threading, each client request creates a


Uses single-threaded event loop
new thread

Blocking I/O model Non-blocking I/O model

High memory and resource usage Lightweight and efficient

Handles many requests


Slower under high load
concurrently

c) Write a program to use SQL SELECT query to show data from a table using Node.js
and MySQL

const mysql = require('mysql');

const connection = mysql.createConnection({


host: 'localhost',
user: 'root',
password: '',
database: 'testdb'
});

connection.connect(err => {
if (err) throw err;
console.log('Connected!');

connection.query('SELECT * FROM students', (err, results) => {


if (err) throw err;
console.log(results);
});
});

d) Explain steps to install Node.js on Windows

1. Download Installer: Go to https://nodejs.org and download the Windows installer


(LTS version).
2. Run Installer: Open the installer and follow the setup wizard steps.
3. Accept License: Accept the license agreement and click "Next".
4. Choose Installation Path: Select the location where Node.js should be installed.
5. Install Tools (Optional): Check the box to install npm and other optional tools.
6. Finish Setup: Click “Install” and then “Finish”.
7. Verify Installation:
8. node -v
9. npm -v

e) Write a program to write to a file in Node.js

const fs = require('fs');

const data = 'This is a test message written to a file.';

// Writing asynchronously
fs.writeFile('output.txt', data, err => {
if (err) throw err;
console.log('File written successfully!');
});

Q-5

a) Write down the connection string of Node.js and MySQL

To connect Node.js with a MySQL database, you first install the MySQL package:

npm install mysql

Connection String Example:

const mysql = require('mysql');

const connection = mysql.createConnection({


host: 'localhost', // Database host
user: 'root', // Username
password: '', // Password
database: 'testdb' // Database name
});

To establish the connection:

connection.connect(err => {
if (err) throw err;
console.log("Connected to MySQL!");
});

b) Explain Event Driven Programming

Event-driven programming is a paradigm where the flow of the program is determined by


events such as user actions (clicks, inputs), messages from other programs, or sensor outputs.
In Node.js, event-driven architecture is handled using the EventEmitter class.

• Node.js runs an event loop that listens for events and triggers callback functions.
• Events are registered using on() or addListener().
• Events are triggered using emit().

Example:

const events = require('events');


const eventEmitter = new events.EventEmitter();

eventEmitter.on('greet', () => {
console.log('Hello! Event received.');
});

eventEmitter.emit('greet');

c) Explain Anonymous function with an example

An anonymous function is a function without a name. It is often used as an argument to


other functions or assigned to variables.

Key Characteristics:

• Used in callbacks.
• Cannot be reused (unless assigned).
• Helps write cleaner and short logic for one-time use.

Example:

setTimeout(function() {
console.log('This is an anonymous function!');
}, 1000);

You can also assign an anonymous function to a variable:

const greet = function() {


console.log('Hello from anonymous function!');
};
greet();

You might also like