PAPER SOLUTIONS
PAPER SOLUTIONS
Q-1
b) Write the syntax to read a file asynchronously in Node.js using the fs module.
const fs = require('fs');
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:
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.
// 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).
Explanation:
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:
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:
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.
Example of requestListener:
const http = require('http');
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.
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();
Explanation:
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.
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();
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.
Synchronous Write:
const fs = require('fs');
Asynchronous Write:
const fs = require('fs');
Explanation:
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.
Explanation:
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');
Explanation:
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.
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';
Explanation:
• 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 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.
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.
• 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.
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).
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:
Example:
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.
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.
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:
c) What is REPL?
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.
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 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
To install the MySQL package using NPM, use the following command:
This will add the MySQL package as a dependency to your project, allowing you to interact
with MySQL databases.
Q-2
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:
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?
Key Advantages:
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).
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.
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');
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.
This file now contains information about the project and its dependencies.
Q-3
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');
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.
The EventEmitter class is part of Node.js' events module. You can use the addListener()
method to attach a listener function to an event.
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.
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.
Example:
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.
Explanation:
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;
};
Explanation:
The traditional web server model and the Node.js process model differ significantly in how
they handle client requests and manage resources.
Key Differences:
Application Example:
// app.js
const square = require('./square');
const sideLength = 5;
const area = square.area(sideLength);
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.
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.
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.
In Node.js, you can use the fs module to create and write data to a file.
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.
Parameters of createConnection():
Example:
const mysql = require('mysql');
Explanation:
This setup allows you to interact with a MySQL database from your Node.js application.
Q-5
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:
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.
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.
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.
module.exports.add = function(a, b) {
return a + b;
};
module.exports.subtract = function(a, b) {
return a - b;
};
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
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:
Example:
$ node
> console.log("Hello, Node.js!");
Hello, Node.js!
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:
• 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:
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}!`);
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);
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:
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);
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.unlinkSync('file-to-delete.txt');
Q-2
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().
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
module.exports.add = function(a, b) {
return a + b;
};
module.exports.subtract = function(a, b) {
return a - b;
};
// app.js
const math = require('./math'); // Import the math.js module
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.
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.
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:
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:
Q-3
How It Works:
Example:
// math.js
module.exports.add = function(a, b) {
return a + b;
};
module.exports.subtract = function(a, b) {
return a - b;
};
// app.js
const math = require('./math'); // Import the math.js module
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.
Example:
// Loading core modules
const fs = require('fs'); // File System module
const http = require('http'); // HTTP module
const path = require('path'); // Path module
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.
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);
Example:
const fs = require('fs');
const data = 'This is some text data that will be written to a file.';
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.
First, ensure you have installed the mysql package using NPM:
Now, you can write the code to select all records from the "employee" table.
Explanation:
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:
Example Code:
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
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); });
});
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');
Explanation:
• This example opens the file example.txt in read/write mode, then truncates it to 5
bytes.
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).
module.exports = Rectangle;
app.js (Main File):
// app.js
const Rectangle = require('./rectangle'); // Import the rectangle module
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.
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.
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.
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:
Example:
const mysql = require('mysql');
connection.connect((err) => {
if (err) throw err;
console.log('Connected to the database');
});
Explanation:
Q-5
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
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.
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:
For example:
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.
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.
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:
NODEJS PAPER-4
Q-1
a) What is the Command to initialize Node Package Manager (NPM)? Write its syntax.
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.
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.
Example:
The fs module in Node.js is used for interacting with the file system, performing tasks such
as:
To add the express dependency to your project using NPM, use the following command:
• Explanation: This command will install express and add it to the dependencies
section of your package.json.
To install the mysql package in a Node.js project, use the following command:
• Explanation: This will install the mysql package and add it to the dependencies
section in package.json.
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:
Example:
const http = require('http');
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
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:
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');
Explanation:
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.
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');
Explanation:
• fs.readFile() reads the file asynchronously and processes it via a callback function
when the operation completes.
• 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:
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
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:
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');
Explanation:
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.
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.
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');
Explanation:
• fs.readFile() reads the file asynchronously and processes it via a callback function
when the operation completes.
• 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:
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
c) Write a program to use SQL SELECT query to show data from a table using Node.js
and MySQL
connection.connect(err => {
if (err) throw err;
console.log('Connected!');
const fs = require('fs');
// Writing asynchronously
fs.writeFile('output.txt', data, err => {
if (err) throw err;
console.log('File written successfully!');
});
Q-5
To connect Node.js with a MySQL database, you first install the MySQL package:
connection.connect(err => {
if (err) throw err;
console.log("Connected to MySQL!");
});
• 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:
eventEmitter.on('greet', () => {
console.log('Hello! Event received.');
});
eventEmitter.emit('greet');
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);