0% found this document useful (0 votes)
8 views20 pages

Awp Gtu

Node.js is an open-source, cross-platform runtime environment for executing JavaScript code outside a browser, commonly used for building back-end services. Key features include single-threaded scalability, fast performance due to the V8 engine, and a large package ecosystem via NPM. It supports real-time applications, microservices, and RESTful APIs, making it suitable for various applications like online chat rooms, streaming media, and CRUD operations.

Uploaded by

Prabhdeep kaur
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)
8 views20 pages

Awp Gtu

Node.js is an open-source, cross-platform runtime environment for executing JavaScript code outside a browser, commonly used for building back-end services. Key features include single-threaded scalability, fast performance due to the V8 engine, and a large package ecosystem via NPM. It supports real-time applications, microservices, and RESTful APIs, making it suitable for various applications like online chat rooms, streaming media, and CRUD operations.

Uploaded by

Prabhdeep kaur
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/ 20

AWP

Q:What is Node.js? Explain the features of Node.js.


ANS:
Node.js:

• Node.js is an open-source and cross-platform runtime environment for executing JavaScript code
outside a browser.
• Node.js is used to build back-end services like APIs for Web Apps or Mobile Apps.
• It’s utilized in production by large companies such as PayPal, Uber, Netflix, Walmart, and many others.
• Example:
// Import the http module
const http = require('http');

// Create a server
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Welcome to the Node.js Tutorial');
});

// Listen on port 3000


server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Features of Node.js.

1. Single-Threaded but Scalable

• Node.js uses one thread to handle many requests.


• Unlike other servers that use multiple threads (which can slow things down), Node.js handles everything
using an event loop, which is fast and efficient.
• This makes it great for apps that need to handle lots of users at the same time.

2. Fast Performance

• Node.js is built on the V8 engine (from Google Chrome).


• It runs JavaScript very fast because it converts code directly into machine code.

3. Perfect for Real-Time Apps

• Ideal for chat apps, online games, and live collaboration tools.
• It can handle many users talking to the server at once — quickly and smoothly.

4. Huge Package Ecosystem (NPM)

• Node.js comes with NPM (Node Package Manager).


• It has over a million ready-made packages you can use — saving time and effort.

5. Strong Community Support

• Thousands of developers are constantly improving Node.js.


• You can find help, tools, and tutorials easily.

6. Cross-Platform

• Works on Windows, macOS, and Linux.


• You can write your code once and run it anywhere.

7. Great for Microservices & APIs

• Node.js is perfect for small, fast services that talk to each other (called microservices).
• Tools like Express.js make it easy to build RESTful APIs.

8. Real-Time Communication

• Supports WebSockets, allowing two-way communication between the server and the browser.
• Great for apps that need live updates (like notifications or stock price changes).

9. Easy JSON Handling

• Node.js works really well with JSON, which is the main format used for APIs and data exchange in web
apps.

10. Backed by Big Companies

• Supported by major companies like Joyent, IBM, and Microsoft.


• This ensures that Node.js is regularly updated and reliable.

Q: What is the use of Node JS?

ANS: The Uses of Node.js are as:

Browser Games
• Ideal for creating real-time applications.
• Utilizes Socket.io and HTML for interactive game development.
• Enables seamless real-time communication and responsive design.
Collecting Data Inputs
• Efficiently collects data from various sources.
• Handles form data collection from browsers.
• Sends data to the backend for storage in databases.
• Enables fetching and processing of stored data.
Streaming Media
• Facilitates fast and efficient media uploading.
• Handles processing of audio and video files.
• Ensures quick upload times and high-speed access.
• Crucial for real-time media processing and streaming.
Online Chat Rooms
• Creates platforms for text chat, voice sharing, and media sharing.
• Handles real-time data for instant communication.
• Ideal for gaming chat rooms and social media platforms.
MERN Stack
• Part of the MERN stack (MongoDB, Express.js, React.js, Node.js).
• Serves as the server-side component.
• Provides efficient data handling and backend integration with MongoDB.
Real-Time Applications
• Suitable for highly scalable and low latency applications.
• Used by platforms like LinkedIn and PayPal.
• Event-driven architecture for quick data processing and response times.
Creation of APIs
• Develops APIs for backend operations.
• Facilitates communication between frontend and backend.
• Handles data processing and logic execution.
• Supports asynchronous operations for robust and scalable API development.

Q: List and discuss various filters used in Angular JS.

ANS:

1. Uppercase Filter
• Add uppercase filter to an expression using pipe character. Here we've added uppercase filter to
print student name in all capital letters.
• Example:
Enter first name:<input type = "text" ng-model = "student.firstName">
Enter last name: <input type = "text" ng-model = "student.lastName">
Name in Upper Case: {{student.fullName() | uppercase}}
2. Lowercase Filter
• Add lowercase filter to an expression using pipe character. Here we've added lowercase filter to
print student name in all lowercase letters.
• Example:
Enter first name:<input type = "text" ng-model = "student.firstName">
Enter last name: <input type = "text" ng-model = "student.lastName">
Name in Lower Case: {{student.fullName() | lowercase}}
3. Currency Filter
• Add currency filter to an expression returning number using pipe character. Here we've added
currency filter to print fees using currency format.
• Example:
Enter fees: <input type = "text" ng-model = "student.fees">
fees: {{student.fees | currency}}
4. Filter
• To display only required subjects, we use subjectName as filter.
• Example:
Enter subject: <input type = "text" ng-model = "subjectName">
Subject:
<ul>
<li ng-repeat = "subject in student.subjects | filter: subjectName">
{{ subject.name + ', marks:' + subject.marks }}
</li>

</ul>

5. OrderBy Filter
• To order subjects by marks, we use orderBy marks.
• Example:
Subject:
<ul>
<li ng-repeat = "subject in student.subjects | orderBy:'marks'">
{{ subject.name + ', marks:' + subject.marks }}
</li>

</ul>

Q: Define REST Architecture in Node JS.


ANS:

• A REST (REpresentational State Transfer) API is a web service that follows the principles of REST
architecture to interact between clients and servers over HTTP.
• It uses standard HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update,
Delete) operations on resources, and data is typically transferred in JSON or XML format.
Principles of REST API

REST APIs are built on six fundamental principles that define their architecture and functionality:

• Statelessness: Each request from a client to the server must contain all the necessary information, and
the server does not store session-related data.
• Client-Server Architecture: The client and server are separate entities, allowing for independent
development and scalability.
• Uniform Interface: A consistent way of accessing resources, typically via standardized HTTP methods
(GET, POST, PUT, DELETE).
• Cacheability: Responses from the server should indicate whether they can be cached to improve
performance.
• Layered System: The architecture should support multiple layers (such as load balancers,
authentication servers, and data storage) without affecting the client-server interaction.
• Code on Demand (Optional): The server can send executable code (like JavaScript) to the client to
enhance functionality, though this is rarely used.
HTTP Methods Used in API
In RESTful APIs, HTTP methods define the actions to be performed on resources. Each HTTP method
corresponds to a specific operation in the CRUD (Create, Read, Update, Delete) cycle. Here’s an explanation of
the commonly used HTTP methods:

GET Method

The GET method is used to retrieve an existing resource from the server. The server responds with the
resource's data, often in JSON or XML format. It is used to read the data.
HTTP GET http://example.com/users
HTTP GET http://example.com/users/123

POST Method

The POST method is used to create a new resource on the server. It sends data to the server as part of the
request body, typically in JSON or XML format. It is used to create a new resource on the server.
HTTP POST http://example.com/users
HTTP POST http://example.com/users/123

PUT Method

The PUT method is used to update an existing resource on the server. It requires the client to send the updated
data in the request body. It is used to update the data.
HTTP PUT http://example.com/users/123
HTTP PUT http://example.com/users/123/name/Anjali

PATCH Method

The PATCH method is used to apply partial modifications to a resource. Unlike PUT, which typically updates
the entire resource, PATCH only sends the changes to be made, making it more efficient in certain scenarios. It
is used to partially update the data on the server.
HTTP PATCH http://example.com/users/123
HTTP PATCH http://example.com/users/123/name/Anjali

DELETE Method

The DELETE method is used to delete a resource from the server. Once executed successfully, it usually returns
a status code indicating the deletion has been completed, such as 200 OK or 204 No Content. It is used to delete
the data.
HTTP DELETE http://example.com/users/123
HTTP DELETE http://example.com/users/123/name/Ravi

Q: Write a short note on Network module in Node JS.


ANS:

The Network module in Node.js provides the ability to work with network operations such as creating servers
and clients for TCP (Transmission Control Protocol) and IPC (Inter-Process Communication).

Though Node.js does not have a module named strictly “network”, these capabilities are available through the
built-in net module.

Features of the net Module

• Enables creation of TCP servers and clients.


• Supports stream-based communication.
• Useful for building low-level networked applications like chat servers, file transfer apps, etc.

Common Functions in netModule

Function/Method Description
net.createServer() Creates a TCP server

net.connect() Connects as a TCP client

socket.write() Sends data to the client or server

socket.on('data') Listens for incoming data

socket.end() Closes the connection

EXAMPLE:

const net = require('net');

const server = net.createServer((socket) => {

socket.write('Welcome to the server!\n');

socket.on('data', (data) => {

console.log('Received:', data.toString());

});

});

server.listen(5000, () => {

console.log('Server listening on port 5000');

});

Q: Discuss NPM (Node Package Manager) in Node JS.

• The NPM is the default package manager for the Node.js.


• It helps the user to manage the JavaScript packages, libraries and dependencies
efficiently.
• With the help of the NPM, we can install, update and manage the packages for the
Node.js.
• Main Uses of NPM:
1. Install Packages
▪ Easily add open-source libraries to your project.
▪ Example: npm install express
2. Manage Dependencies
▪ Keeps track of all packages your project uses in a file called package.json.
3. Run Scripts
▪ You can automate tasks like running the server, testing, and building.
▪ Example:
"scripts": {
"start": "node app.js"
}
4. Global vs Local Installation
▪ Local: Used only in your project.
▪ Example:npm install express

Q: What is stream? Write node JS code to read from stream.

ANS:A stream in Node.js is a way to handle reading or writing data sequentially—chunk by chunk—
instead of loading it all into memory at once.

Streams are useful for:

• Reading/writing large files


• Streaming audio or video
• Network communication

Types of Streams

1. Readable – Stream you can read from (e.g., file input)


2. Writable – Stream you can write to (e.g., file output)
3. Duplex – Both readable and writable (e.g., TCP socket)
4. Transform – A duplex stream that can modify or transform data as it is written or read (e.g.,
compression)

Node.js Example: Reading from a File Using a Readable Stream


Q: Write the applications of Angular JS.
ANS:

1. Single Page Applications (SPAs)

• AngularJS is well-suited for building SPAs where content updates dynamically without reloading the
entire page.
• Example: Gmail, Facebook-like interfaces.

2. Dynamic Web Applications

• AngularJS allows two-way data binding, making it ideal for applications that need to update the UI in
real time based on user input or data changes.

3. CRUD Applications

• Used to build apps that perform Create, Read, Update, Delete operations.
• Example: Employee management systems, contact managers, admin panels.

4. Form-Based Applications

• With built-in support for form validation, AngularJS simplifies creating applications with dynamic
forms and user inputs.
• Example: Registration forms, feedback forms, and login forms.

5. Real-Time Applications

• AngularJS is used in applications that need to display data in real time.


• Example: Chat apps, live dashboards, stock price trackers.

6. Content Management Systems (CMS)

• You can build lightweight and efficient CMS tools using AngularJS, especially when combined with
APIs.
• Example: Blog or portfolio site admin panels.

7. E-commerce Applications

• AngularJS is used to develop user-friendly, responsive interfaces for online shopping.


• Features like product filtering, dynamic pricing, and cart updates work well with Angular’s features.

8. Enterprise Web Applications

• Many internal company tools use AngularJS for managing large data and user interactions.
• Example: Project tracking tools, employee portals.

Q: Write a note on MongoDB.

MongoDB is a popular, open-source NoSQL database designed for handling large volumes of unstructured
or semi-structured data. Instead of storing data in tables like traditional relational databases, MongoDB stores
data in flexible, JSON-like documents.

Key Features of MongoDB

1. Document-Oriented
a. Data is stored in collections (similar to tables) and each item is a document (similar to a row).
b. Documents use BSON (Binary JSON), which supports nested data and arrays.
2. Schema-less
a. Collections don’t require a fixed schema.
b. Each document in a collection can have a different structure.
3. High Performance
a. Designed for high read/write throughput.
b. Supports indexing, replication, and horizontal scaling.
4. Scalability
a. Built to scale across many servers using sharding.
b. Suitable for big data applications.
5. Rich Query Language
a. Supports powerful queries using JavaScript-like syntax.
b. Example:db.users.find({ age: { $gt: 25 } });
6. Integration with Node.js
a. MongoDB works well with JavaScript-based environments like Node.js using drivers like
Mongoose or the native MongoDB Node.js driver.

Q: Discuss: sessions and cookies.

ANS:

Cookies

• Small pieces of data stored on the user’s browser.


• Sent with every HTTP request to the server.
• Often used to remember user preferences, login status, etc.

Characteristics:

• Stored on the client-side (browser).


• Limited in size (typically 4KB).
• Can be set to expire after a certain time.
• Can be read by both client and server (unless marked as HttpOnly).

Example Use Cases:

• Remembering language settings.


• Keeping user logged in (with tokens).
• Tracking user behavior (analytics).

Example in JavaScript: document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2025 23:59:59 GMT";

Sessions

• A way to store temporary data on the server for each user.


• The server assigns a unique session ID, often stored in a cookie on the client.
• The actual data is stored on the server.

Characteristics:

• Stored on the server-side.


• More secure, as data is not exposed to the browser.
• Automatically expires after a time of inactivity or logout.

Example Use Cases:

• Storing user login info after authentication.


• Shopping cart data.
• User-specific temporary settings.

Example in Node.js with Express:

const session = require('express-session');

app.use(session({

secret: 'mysecret',

resave: false,

saveUninitialized: true

}));
Q: Write Node JS programs for database connectivity with MongoDB including insert operation in
MySQL database.
Q: Create a webpage using Angular JS that displays details of students'objects (such as Enrollment No.,
Name, Semester, Branch, MobileNumber, Email Address, Address etc.) in a tabular format with
appropriate CSS effects.
Q: Create a HTML form using bootstrap controls that will accept EnrollmentNo., Name, Semester,
Branch, Mobile Number, Email, Address etc. fromthe student, combine and display them on the
page when button is clickedalso validate an Email address using Javascript.
Q: Explain piping and chaining of streams with suitable example.

ANS:

Piping:

• Piping is a method used to connect the output of one stream to the input of another.
• It’s commonly used to read from a readable stream and write to a writable stream without manually
handling events like data, end, etc.
• Think of it like:
Source → Transform (optional) → Destination

• Example: Copying a file using piping

Chaining:

• Chaining is the process of connecting multiple stream operations together.


• It is often used with transform streams such as compression, encryption, or data manipulation.
• Example: Compressing a file using chaining

Here:

• fs.createReadStream() → Reads from input.txt


• zlib.createGzip() → Compresses the data
• fs.createWriteStream() → Writes to input.txt.gz

Q: Explain an event-loop in Node.js.

ANS: The event loop in Node.js is a mechanism that allows asynchronous tasks to be handled efficiently
without blocking the execution of other operations. It:

• Executes JavaScript synchronously first and then processes asynchronous operations.


• Delegates heavy tasks like I/O operations, timers, and network requests to the libuv library.
• Ensures smooth execution of multiple operations by queuing and scheduling callbacks efficiently.

Phases of the Event loop


The event loop in Node.js consists of several phases, each of which performs a specific task. These phases
include:

1. Timers Phase: This phase processes timers that have been set using setTimeout() and setInterval().

1. Pending Callbacks: This phase executes I/O-related callbacks that were deferred from the previous
loop cycle.
2. Idle, Prepare (Internal use only):This phase is used internally by Node.js for background tasks.

3. Poll Phase (Main Phase): The Poll phase executes most of the tasks like- I/O, file reading, HTTP
requests and much more.

4. Check Phase: This phase processes any setImmediate() callbacks that have been added to the message
queue.

5. Close Callbacks Phase: This phase executes callbacks for closed connections like sockets, streams, and
event emitters.

Q: What is an error-first callback?


ANS:

• Error-first callback in Node.js is a function that returns an error object whenever any successful data is
returned by the function.
• The first argument is reserved for the error object by the function. This error object is returned by
the first argument whenever any error occurs during the execution of the function.
• The second argument is reserved for any type of successful data returned by the function. The
error object is set to null when no error occurs.
• EXAMPLE:

Q: Explain Node JS buffers in detail.


ANS:

Buffer in Node is a built-in object used to perform operations on raw binary data. The buffer class allows
us to handle the binary data directly.

Syntax: const buf = Buffer.alloc(10); // Allocates a buffer of 10 bytes.

Buffer Methods:

No Method Description

1 Buffer.alloc(size) It creates a buffer and allocates size to it.

2 Buffer.from(initialization) It initializes the buffer with given data.

3 Buffer.write(data) It writes the data on the buffer.

4 toString() It read data from the buffer and returned it.

5 Buffer.isBuffer(object) It checks whether the object is a buffer or not.

6 Buffer.length It returns the length of the buffer.

7 Buffer.copy(buffer,subsection
It copies data from one buffer to another.
size)
8 Buffer.slice(start,
It returns the subsection of data stored in a buffer.
end=buffer.length)

9 Buffer.concat([buffer,buffer]) It concatenates two buffers.

Q: What is REPL? What purpose it is used for?


ANS:

REPL is like a JavaScript playground in your terminal. If you type the code, REPL runs it, shows you the result,
and then waits for your next command. It's a loop:

• READ: You type some JavaScript code into the terminal, and REPL reads what you typed.
• EVAL: REPL runs (evaluates) your code.
• PRINT: REPL shows you the result of your code.
• LOOP: REPL goes back to step 1, waiting for you to type more code. This loop continues until you quit
REPL.

Starting REPL in the Terminal or Command Prompt

• Open your terminal (for UNIX/Linux) or Command Prompt (for Windows).


• Type node and press 'Enter' to start the REPL.

The REPL has started and is demarcated by the '>' symbol. Various operations can be performed on the REPL.
Below are some of the examples to get familiar with the REPL environment.
Example:
Q: Write code to perform update and delete operations on Employee database using Node.js and
MongoDB.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy