[go: up one dir, main page]

0% found this document useful (0 votes)
28 views13 pages

Node.js Exam

The document provides a comprehensive guide on Node.js exam answers, covering key topics such as initializing NPM, adding dependencies, updating MySQL records, writing to files, and explaining the Node.js process model. It includes code examples, explanations, and analogies to simplify complex concepts. Additionally, it outlines advantages of Node.js, event-driven programming, and core modules, along with steps for handling HTTP requests and installing Node.js on Windows.
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)
28 views13 pages

Node.js Exam

The document provides a comprehensive guide on Node.js exam answers, covering key topics such as initializing NPM, adding dependencies, updating MySQL records, writing to files, and explaining the Node.js process model. It includes code examples, explanations, and analogies to simplify complex concepts. Additionally, it outlines advantages of Node.js, event-driven programming, and core modules, along with steps for handling HTTP requests and installing Node.js on Windows.
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/ 13

Node.

js Exam Answers
This Questions are related to Subject - Node JS , Make sure
to answer each question in either 5-6 bullet points or table,
keep it **very simple** to understand but at the same time
these answers will be written in exams. you can also explain
in analogy if the answer is difficult to learn but make sure
the analogy is not a part of the real answer it's just an extra
point

Got it! Drop your Node.js questions, and I'll give you clear, exam-friendly answers with
optional analogies for tough topics.

What is the command to initialize node package manager


(NPM)? Write its syntax.

Command to Initialize Node Package Manager (NPM):


sh

npm init

Syntax:

sh

npm init [options]

Explanation:
npm init → Starts the package initialization process.

npm init -y → Skips questions and uses default values.

npm init --scope=@yourname → Initializes a scoped package.

Analogy: Think of npm init like setting up a new profile on a website—you fill in some
details (or use defaults) before using it.

Write a command to add dependency 'express' using NPM.


(2 marks)

1/13
Command to Add express as a Dependency:
sh

npm install express

Alternative Short Form:

sh

npm i express

This installs express and adds it to the dependencies section of package.json .

Write a program to update table records using Node.js and


MySQL. (4 marks)

Here’s a simple Node.js program to update table records using MySQL:

Program to Update Table Records

javascript

const mysql = require('mysql');

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

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

// SQL query to update a record


const sql = `UPDATE users SET name = 'John Doe' WHERE id = 1`;

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

2/13
if (err) throw err;
console.log('Record Updated:', result.affectedRows);
});

connection.end();
});

Explanation:
Connects to MySQL database.

Runs an UPDATE query to change the name of a user where id = 1 .

Prints the number of affected rows.

Closes the connection.

Let me know if you need any modifications! 🚀


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

Program to Write to a File in Node.js

javascript

const fs = require('fs');

const content = 'Hello, this is a test file!';

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

Explanation:
Imports the fs (File System) module.

Defines content to be written to the file.

Uses fs.writeFile() to write the content into output.txt .

If successful, logs "File written successfully!".

3/13
Analogy: This is like writing a note in a diary— fs.writeFile creates the note, and if there's
an issue (like a missing pen), it throws an error.

Explain Node.js Process Model with the help of a diagram

Node.js Process Model


Node.js follows an event-driven, non-blocking I/O model, making it efficient for handling
multiple requests.

Steps in Node.js Process Model:


1. Client Request → Multiple clients send requests (e.g., reading a file, querying a
database).

2. Event Loop → Node.js listens for requests and processes them asynchronously.

3. Single Thread Execution → A single thread handles requests, delegating heavy tasks to
worker threads when needed.

4. Non-blocking I/O → Operations like file reading and database queries do not block
execution; they use callbacks/promises.

5. Response Sent → Once processing is complete, Node.js sends the response back to the
client.

Diagram Representation:
arduino

┌───────────────┐
│ Client 1 │
├───────────────┤
│ Client 2 │ → Request → ┌───────────────┐
├───────────────┤ │ Event Loop │
│ Client 3 │ → Request → │ (Handles I/O) │ → Processes request →
└───────────────┘ └───────────────┘ Sends response

4/13
Analogy:
Think of Node.js as a waiter in a restaurant. Instead of waiting for one dish to cook before
taking the next order, the waiter takes multiple orders, gives them to the kitchen (worker
threads), and serves food as soon as it's ready.

1. REPL

Marks: 2 each

Sections: Q1

Example: "What is REPL?"

2. Core Modules of Node.js

Marks: 2 each

Sections: Q1

Example: "List any four core modules of Node.js."

1. REPL (Read-Eval-Print Loop)


REPL is an interactive shell in Node.js.

It allows users to execute JavaScript code line by line.

It stands for Read, Eval, Print, Loop.

Used for quick testing and debugging.

Can be started by running node in the terminal.

Example:

sh

$ node
> console.log("Hello");
Hello

5/13
2. Core Modules of Node.js
Core modules are built-in modules in Node.js.

They do not require installation ( require('<module>') is enough).

Examples of core modules:

1. fs – File System (Handles file operations).

2. http – Creates web servers.

3. path – Handles file paths.

4. os – Provides OS-related information.

Let me know if you need further details! 🚀


Advantages of Node.js

Advantages of Node.js
1. Asynchronous & Non-blocking → Handles multiple requests simultaneously, improving
performance.

2. Fast Execution → Uses Google V8 Engine, making JavaScript code execution very fast.

3. Single Programming Language → Uses JavaScript for both frontend and backend,
simplifying development.

4. Scalability → Handles large-scale applications efficiently using event-driven architecture.

5. Large Community Support → Many open-source libraries and active developer support.

6. Lightweight → Uses fewer resources compared to traditional server-side technologies.

Analogy: Node.js is like a fast food drive-thru—it takes multiple orders at once and serves
them efficiently without making customers wait in line. 🚀
Write a program using addListener() method of
EventEmitter.

Program Using addListener() Method of EventEmitter

javascript

const EventEmitter = require('events');

6/13
// Create an EventEmitter object
const myEmitter = new EventEmitter();

// Add a listener using addListener()


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

// Trigger the event


myEmitter.emit('greet');

Explanation:
Imports the events module.

Creates an instance of EventEmitter .

Uses addListener() to attach a listener to the 'greet' event.

Emits (triggers) the 'greet' event, calling the listener function.

Note: addListener() works the same as on() , but on() is preferred in modern code.

Module Exports/Purpose

Module Exports in Node.js

Purpose:

Allows exporting functions, objects, or variables from one file to another.

Helps in creating reusable and modular code.

Uses module.exports or exports to define what should be shared.

Example:

File: math.js (Exporting Module)

javascript

module.exports.add = (a, b) => a + b;

File: app.js (Importing Module)

javascript

7/13
const math = require('./math');
console.log(math.add(5, 3)); // Output: 8

Analogy:
Think of module.exports like a menu in a restaurant—it defines what dishes (functions) are
available for customers (other files) to order.

Traditional vs Node.js Web Server Model

Traditional vs Node.js Web Server Model

Feature Traditional Web Server Node.js Web Server

Threading Multi-threaded Single-threaded, event-driven

Handling Each request gets a separate Non-blocking, handles multiple requests


Requests thread efficiently

Performance Slower due to thread switching Faster due to asynchronous processing

Resource Usage High (creates new threads) Low (uses event loop)

Scalability Limited, needs more hardware Highly scalable without extra hardware

Example Apache, PHP Node.js with Express.js

Analogy:
Traditional Server → Like a restaurant with one waiter per customer, leading to delays
if too many customers arrive.

Node.js Server → Like a fast food counter where one worker takes multiple orders
and serves them efficiently. 🚀
Explain Event-Driven Programming.

Event-Driven Programming in Node.js

Definition:

A programming paradigm where the flow of execution is determined by events (e.g.,


user actions, system signals).

8/13
Node.js uses an Event Loop to handle multiple events asynchronously.

Key Concepts:

1. Events → Actions like clicks, file reads, or HTTP requests.

2. Event Emitters → Objects that trigger and listen to events ( EventEmitter in Node.js).

3. Event Handlers → Functions executed when an event occurs.

4. Non-Blocking Execution → Other code runs while waiting for events.

Example:

javascript

const EventEmitter = require('events');


const myEmitter = new EventEmitter();

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

myEmitter.emit('greet');

Analogy:
Think of event-driven programming like a doorbell system—the bell rings (event), and
someone answers (handler), without constantly checking the door. 🚪🔔
Explain Anonymous function with an example.

Anonymous Function in JavaScript & Node.js

Definition:

A function without a name.

Used for short-term tasks, like callbacks or event handling.

Can be assigned to variables or passed as arguments.

Example 1: Assigned to a Variable

9/13
javascript

const greet = function() {


console.log("Hello, World!");
};
greet(); // Output: Hello, World!

Example 2: Used as a Callback

javascript

setTimeout(function() {
console.log("This runs after 2 seconds.");
}, 2000);

Analogy:
An anonymous function is like a one-time-use delivery guy—he delivers the package
(executes the function) and is never seen again! 🚀📦
1. File System Module Usage

Marks: 2 each

Sections: Q1

Example: "For which tasks is the File System module used?"

2. Buffer Module Functions

Marks: 2 each

Sections: Q1/Q5

Example: "Write any two functions of Buffer used in


Node.js."

3. Handling HTTP Requests

10/13
Marks: 2/4 each

Sections: Q1/Q2

Example: "Write steps to handle HTTP requests while


creating a web server."

4. Installing Node.js on Windows

Marks: 4 each

Sections: Q4

Example: "Explain steps to install Node.js on Windows."

1. File System (FS) Module Usage


The fs module is used to handle file operations in Node.js.

Common Tasks:

1. Reading files ( fs.readFile() ).

2. Writing files ( fs.writeFile() ).

3. Appending data to files ( fs.appendFile() ).

4. Deleting files ( fs.unlink() ).

5. Creating and managing directories ( fs.mkdir() , fs.rmdir() ).

2. Buffer Module Functions


The Buffer module is used to handle binary data in Node.js.

Two Common Functions:

1. Buffer.alloc(size) → Creates a new buffer of the given size.

javascript

let buf = Buffer.alloc(10); // Allocates 10 bytes

11/13
2. Buffer.from(string) → Creates a buffer from a string.

javascript

let buf = Buffer.from("Hello");


console.log(buf); // Outputs binary data

3. Steps to Handle HTTP Requests in a Node.js Server


1. Import HTTP Module:

javascript

const http = require('http');

2. Create a Server:

javascript

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


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

3. Listen on a Port:

javascript

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

4. Process Client Requests & Send Responses.

4. Steps to Install Node.js on Windows


1. Download Installer → Visit nodejs.org and download the Windows installer.

2. Run Installer → Open the downloaded .msi file and follow the installation steps.

12/13
3. Choose Components → Ensure Node.js and npm (Node Package Manager) are
selected.

4. Set Environment Variables → The installer sets up the required system paths.

5. Verify Installation:

Open Command Prompt and run:


sh

node -v
npm -v

If versions appear, installation is successful. 🚀


Let me know if you need any modifications!

13/13

You might also like