0% found this document useful (0 votes)
55 views30 pages

FSD 2

Uploaded by

Sakib Mulani
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)
55 views30 pages

FSD 2

Uploaded by

Sakib Mulani
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/ 30

Unit 1

What is the MEAN Stack?


The MEAN stack is a technology stack used for building dynamic web applications. It
consists of four main technologies:
- MongoDB
- Express.js
- Angular (formerly AngularJS)
- Node.js
List out any 4 advantages of the MEAN Stack.
1. JavaScript Everywhere: How does the MEAN stack leverage JavaScript for both front-
end and back-end development?
2. Full Stack Development: How does expertise in both front-end and back-end
technologies benefit MEAN stack developers?
3. JSON-based Communication: How does the use of JSON simplify data interchange
within the MEAN stack?
4. Scalability and Performance: What components of the MEAN stack contribute to
scalability and high performance of web applications?
List out the different technologies that make up the MEAN stack.
The MEAN stack comprises which technologies, and what are their respective roles in
web application development?
- MongoDB
- Express.js
- Angular (formerly AngularJS)
- Node.js
Unit 2
ES6 (ECMAScript 2015)
ES6, short for ECMAScript 2015, is a major update to the JavaScript language
specification, which was standardized by the ECMA International standards
organization. It introduced several new features and enhancements to JavaScript,
aimed at making the language more expressive, readable, and powerful. Some key
features introduced in ES6 include:
- Arrow Functions
- Template Literals
- Let and Const Keywords
- Classes and Modules
- Destructuring Assignments
- Enhanced Object Literals
- Promises and Generators
- Spread and Rest Operators
`let` and `const` Keywords
- `let`: The `let` keyword allows the declaration of block-scoped variables in
JavaScript. Variables declared with `let` can be reassigned, but they are only
accessible within the block in which they are defined.

Example:
```javascript
let count = 10;
if (true) {
let count = 20; // This is a different variable than the one outside the block
console.log(count); // 20
}
console.log(count); // 10
```
- `const`: The `const` keyword is used to declare constants in JavaScript. Constants
must be initialized with a value and cannot be reassigned or redeclared. However, for
objects and arrays declared with `const`, their properties or elements can be modified.

Example:
```javascript
const PI = 3.14159;
// PI = 3.14; // Error: Assignment to constant variable
const colors = ['red', 'green', 'blue'];
colors.push('yellow'); // Allowed, as we're modifying the array contents
Spread Operator (`...`) in ES6
The spread operator (`...`) in ES6 is used to expand iterable objects (like arrays or
strings) into individual elements. It allows us to unpack elements from an array or object
and use them in places where multiple elements or key-value pairs are expected.

Example of spread operator with arrays:


```javascript
const numbers = [1, 2, 3];
const moreNumbers = [...numbers, 4, 5]; // [1, 2, 3, 4, 5]
```
TypeScript
TypeScript is a superset of JavaScript developed by Microsoft that adds static typing
(type checking) to the language. It compiles to plain JavaScript and aims to make large-
scale JavaScript application development more manageable and maintainable by
providing features such as:
- Static Typing: Supports types like string, number, boolean, etc.
- Interfaces and Classes: Supports object-oriented programming concepts.
- Modules: Allows organizing code into reusable components.
- Generics: Enables writing flexible and reusable code components.
- Compile-time Type Checking: Helps catch errors early in the development process.

Ways to Declare Variables in TypeScript


In TypeScript, variables can be declared using the following ways:
1. Using `var`: Declares a variable with function scope.
2. Using `let`: Declares a block-scoped variable.
3. Using `const`: Declares a block-scoped constant (immutable variable).
4. Type Annotations: Provides explicit type annotations for variables.
Example:
```typescript
let message: string = 'Hello';
const PI: number = 3.14;
```
These declarations enable TypeScript to perform type checking during development,
enhancing code reliability and maintainability.
Let's address each of these questions:
Compare and Contrast Syntax of ES6 Function with TypeScript

In ES6 (ECMAScript 2015), the syntax for defining functions was enhanced with the
introduction of arrow functions (`=>`). Here's a comparison between ES6 and
TypeScript syntax for functions:

ES6 Function Syntax:


```javascript
// ES6 function
const greet = (name) => {
return `Hello, ${name}!`;
};
```

TypeScript Function Syntax:


```typescript
// TypeScript function
const greet = (name: string): string => {
return `Hello, ${name}!`;
};
```

In TypeScript, we can add type annotations to function parameters and return types,
enhancing the clarity and maintainability of the code.

Discuss the Symbol in ES6 with an Example

The spread operator (`...`) in ES6 is used to expand iterable objects like arrays into
individual elements. It can also be used for object spreading to clone or merge objects.

Example of Spread Operator in Arrays:


```javascript
const numbers = [1, 2, 3];
const moreNumbers = [...numbers, 4, 5]; // [1, 2, 3, 4, 5]
```

Example of Spread Operator in Objects:


```javascript
const person = { name: 'John', age: 30 };
const newPerson = { ...person, city: 'New York' };
// newPerson: { name: 'John', age: 30, city: 'New York' }
```
Compare and Contrast Example of ES6 Arrow Function with TypeScript

ES6 Arrow Function:


```javascript
const multiply = (a, b) => a b;
console.log(multiply(5, 3)); // 15
```

TypeScript Arrow Function:


```typescript
const multiply = (a: number, b: number): number => a b;
console.log(multiply(5, 3)); // 15
```

In TypeScript, arrow functions can have type annotations for parameters and return
types, providing additional type safety and clarity.

Differences Between TypeScript and JavaScript

Some key differences between TypeScript and JavaScript include:


- TypeScript supports static typing with type annotations, whereas JavaScript is
dynamically typed.
- TypeScript provides features like interfaces, classes, enums, and modules which are
not native to JavaScript.
- TypeScript code needs to be transpiled into JavaScript using a compiler like `tsc`
before execution.
- TypeScript helps catch errors during development with compile-time type checking.

Steps to Execute "Hello World" Program in TypeScript

To execute a "Hello World" program in TypeScript, follow these steps:


1. Install TypeScript globally using npm:
```
npm install -g typescript
```
2. Create a TypeScript file (e.g., `hello.ts`) with the following code:
```typescript
const message: string = 'Hello, TypeScript!';
console.log(message);
```
3. Compile the TypeScript file to JavaScript using the TypeScript compiler (`tsc`):
```
tsc hello.ts
```
4. This will generate a JavaScript file (`hello.js`) based on the TypeScript code.
5. Run the generated JavaScript file using Node.js:
```
node hello.js
```

Advantages of Using TypeScript

Some advantages of using TypeScript over JavaScript include:


- Static Typing: Helps catch type-related errors at compile time.
- Enhanced Tooling: TypeScript provides better IDE support and IntelliSense.
- Readability and Maintainability: Type annotations and interfaces make code more
understandable and maintainable.
- Object-Oriented Features: Supports classes, interfaces, and modules for organizing
code.
- Compatibility: TypeScript is a superset of JavaScript, meaning all JavaScript code is
valid TypeScript.
Let's address each of these topics:

Template Literals in ES6

Template literals in ES6 are a way to create strings that allow embedded expressions
and multiline strings. They are enclosed by backticks (` `) instead of single or double
quotes.

Example of Template Literals:


```javascript
const name = 'John';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, John!
```

Destructuring Assignment in ES6

Destructuring assignment in ES6 allows you to unpack values from arrays or objects
into distinct variables.

Example of Destructuring Assignment:


```javascript
// Array destructuring
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a, b, c); // Output: 1 2 3

// Object destructuring
const person = { firstName: 'John', lastName: 'Doe' };
const { firstName, lastName } = person;
console.log(firstName, lastName); // Output: John Doe
```
Creating a Class in ES6

In ES6, you can create classes using the `class` keyword.

Example of Class in ES6:


```javascript
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

greet() {
return `Hello, ${this.firstName} ${this.lastName}!`;
}
}

const john = new Person('John', 'Doe');


console.log(john.greet()); // Output: Hello, John Doe!
```

Inheritance in ES6

Inheritance in ES6 is achieved using the `extends` keyword to create subclasses (child
classes) that inherit from a superclass (parent class).

Example of Inheritance in ES6:


```javascript
class Animal {
constructor(name) {
this.name = name;
}

speak() {
return `${this.name} makes a noise`;
}
}

class Dog extends Animal {


speak() {
return `${this.name} barks`;
}
}

const myDog = new Dog('Buddy');


console.log(myDog.speak()); // Output: Buddy barks
```
Modules in TypeScript

Modules in TypeScript are used to organize code into reusable components and
facilitate better code structure and maintainability. TypeScript supports both
CommonJS (`require`/`exports`) and ES6 (`import`/`export`) module formats.

Type Narrowing in TypeScript

Type narrowing in TypeScript refers to refining the type of a variable within a conditional
block based on type predicates or guards.

TypeScript Decorator

A TypeScript decorator is a special kind of declaration that can be attached to classes,


methods, properties, or parameters to modify their behavior or add metadata. There are
different types of decorators in TypeScript, such as class decorators, method
decorators, property decorators, and parameter decorators.

Example of Class Decorator:


```typescript
function logClass(target: Function) {
console.log(`Class ${target.name} is being logged`);
}

@logClass
class MyClass {
// Class implementation
}
```

Generics in TypeScript

Generics in TypeScript allow you to create reusable components that can work with a
variety of data types. They enable you to define functions, classes, or interfaces with
placeholders for types that are specified when the component is used.

Interfaces in TypeScript

Interfaces in TypeScript define the structure of objects and specify the types of their
properties and methods.

Type Guards in TypeScript

Type guards in TypeScript are used to narrow down the type of a variable within a
conditional block based on runtime checks.
TypeScript Data Types

1. `unknown`: Represents a type-safe counterpart of `any`. Values of type `unknown`


can hold any value, but you must perform type checks before operating on them.
2. `any`: Represents any type and allows any operations on its values without type
checking.
3. `void`: Represents the absence of any type and is commonly used as the return type
of functions that do not return a value.
4. `never`: Represents the type of values that never occur, such as functions that
always throw errors or never return.

I hope this helps clarify these TypeScript and ES6 concepts. If you have further
questions or need more examples, feel free to ask!
Unit 3
Certainly! Let's address each of these questions related to AngularJS:

What `ng-app` does in an AngularJS Application

The `ng-app` directive in AngularJS is used to define the root element (or the "root
scope") of an AngularJS application within an HTML document. It marks the beginning of
the AngularJS application and specifies which part of the HTML document should be
managed by AngularJS.

Example:
```html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS App</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyController">
<!-- AngularJS content goes here -->
</div>
</body>
</html>
```
In this example, `ng-app="myApp"` specifies that the `myApp` module is the root of
the AngularJS application.

Define Scope in AngularJS

In AngularJS, the scope refers to the context in which data is accessible to the AngularJS
application. Scopes are hierarchical and prototypically inherited, forming a tree-like
structure that mirrors the DOM structure of the application.
Define AngularJS and Its Key Features

AngularJS is an open-source JavaScript framework developed and maintained by


Google. It is used for building dynamic web applications and implements the Model-
View-Controller (MVC) architectural pattern.

Key Features of AngularJS:


- Two-way Data Binding: Automatically synchronizes data between the model and the
view.
- Directives: Extends HTML with custom attributes and behaviors.
- Dependency Injection: Promotes modular and reusable code by injecting
dependencies into components.
- Templates: Uses HTML templates to define views.
- Routing: Supports client-side routing to create Single Page Applications (SPAs).
- Testing: Provides built-in support for unit testing and end-to-end testing.

Define `$scope` in AngularJS

In AngularJS, the `$scope` is an object that binds the "controller" and the "view" in the
MVC architecture. It acts as a data bridge between the controller and the view, allowing
data to be shared and manipulated.

Define `$rootScope` in AngularJS

The `$rootScope` is the top-level scope created for an AngularJS application. It is the
parent scope for all other scopes in the application and is used to store global data or
methods that need to be accessible across different parts of the application.

Example:
```javascript
app.controller('MyController', function($scope, $rootScope) {
$scope.name = 'John';
$rootScope.company = 'XYZ Corp';
});
```
In this example, `$scope.name` is accessible within the controller's scope, while
`$rootScope.company` is accessible globally across the entire AngularJS application.

I hope this clarifies these concepts in AngularJS. If you have further questions or need
more information, feel free to ask!
Let's address each of these questions related to AngularJS:

Advantages of AngularJS Over Other JavaScript Frameworks

1. Two-Way Data Binding: AngularJS implements two-way data binding, which


automatically syncs data between the model (JavaScript objects) and the view (HTML).
This reduces the need for manual DOM manipulation and makes it easier to keep data
in sync.

2. Dependency Injection (DI): AngularJS has a built-in dependency injection system that
promotes modularity and reusability of code. It allows components to be easily tested
and decoupled, leading to more maintainable applications.

AngularJS MVC Architecture

AngularJS follows the Model-View-Controller (MVC) architectural pattern, where:


- Model: Represents the data of the application. In AngularJS, the model is typically
JavaScript objects that are manipulated by controllers.
- View: Represents the user interface (HTML templates) that the user interacts with.
Views are populated with data from the model using controllers.
- Controller: Handles the business logic of the application and interacts with both the
model and the view. Controllers update the model based on user interactions and
update the view to reflect changes in the model.

Directives in AngularJS

Directives in AngularJS are special HTML attributes that modify the behavior or
appearance of DOM elements. They extend the functionality of HTML by allowing you to
create custom, reusable components and behaviors.

Examples of AngularJS Directives:


- `ng-model`: Binds an input field's value to a variable in the model.
- `ng-repeat`: Iterates over a collection and generates HTML elements based on each
item.
- `ng-click`: Executes a function when an element is clicked.
- `ng-show` / `ng-hide`: Shows or hides an element based on a condition.

Example:
```html
<div ng-controller="MyController">
<input type="text" ng-model="name">
<p>Hello, {{ name }}!</p>

<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>

<button ng-click="addItem()">Add Item</button>


</div>
```
In this example, `ng-model`, `ng-repeat`, and `ng-click` are AngularJS directives that
enhance the functionality of HTML elements.
Directives are a powerful feature of AngularJS that enable the creation of dynamic and
interactive web applications.

If you have more questions or need further clarification, feel free to ask!
Let's address each of these topics related to AngularJS:

AngularJS Components with Example

AngularJS Components are a more modern way of defining UI components compared to


using controllers and directives. Components encapsulate the template, styles, and
behavior of a part of the user interface into a reusable, self-contained unit.

Example of AngularJS Component:


```html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Components Example</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="myApp">

<my-component></my-component>

<script>
angular.module('myApp', [])
.component('myComponent', {
template: '<h1>Hello, {{ $ctrl.name }}!</h1>',
controller: function() {
this.name = 'John';
}
});
</script>

</body>
</html>
```
In this example, we define a custom component named `myComponent` using the
`.component()` method. The component consists of a template (`<h1>Hello, {{
$ctrl.name }}!</h1>`) and a controller that sets the `name` property.

Controller in AngularJS with Example

A controller in AngularJS is a JavaScript constructor function that is used to augment


the AngularJS scope. It is responsible for handling business logic, managing data, and
interacting with the view.
Example of AngularJS Controller:
```html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Controller Example</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="MyController">

<p>{{ greeting }}</p>

<script>
angular.module('myApp', [])
.controller('MyController', function($scope) {
$scope.greeting = 'Hello, AngularJS!';
});
</script>

</body>
</html>
```
In this example, we define an AngularJS controller named `MyController` using the
`.controller()` method. The controller sets the `greeting` property on the scope, which
is displayed in the view using interpolation (`{{ greeting }}`).

Module in AngularJS with Example

A module in AngularJS is a container for different parts of an application like controllers,


services, directives, etc. It helps in organizing and managing dependencies.

Example of AngularJS Module:


```html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Module Example</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="myApp">

<div ng-controller="MyController">
<p>{{ message }}</p>
</div>
<script>
angular.module('myApp', [])
.controller('MyController', function($scope) {
$scope.message = 'Welcome to AngularJS Modules!';
});
</script>

</body>
</html>
```
In this example, we define an AngularJS module named `myApp` using the `.module()`
method. We then create a controller within the module to set the `message` property
on the scope.

Syntax and Purpose of AngularJS Directives

1. `ng-model`: Binds an input element's value to a variable in the model. It establishes


a two-way data binding between the view and the controller.
2. `ng-bind`: Binds the content of an HTML element to a variable in the model. It is
used for one-way data binding where changes in the model are reflected in the view.
3. `ng-repeat`: Iterates over a collection and generates HTML elements based on each
item. It is used to render lists or tables dynamically.
4. `ng-init`: Initializes variables in the scope. It is used to execute expressions and
initialize data when the element is initialized.

AngularJS Pipes (Filters) with Example

AngularJS pipes (or filters) are used to format data displayed to the user. They transform
the data in the template before displaying it.

Example of AngularJS Pipes:


```html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Pipes Example</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="myApp">

<p>{{ price | currency }}</p>


<p>{{ currentDate | date:'fullDate' }}</p>
<p>{{ user | json }}</p>

<script>
angular.module('myApp', [])
.controller('MyController', function($scope) {
$scope.price = 100;
$scope.currentDate = new Date();
$scope.user = { name: 'John', age: 30 };
});
</script>

</body>
</html>
```
In this example:
- `currency`: Formats the `price` variable as a currency value.
- `date:'fullDate'`: Formats the `currentDate` variable as a full date string.
- `json`: Formats the `user` variable as a JSON string.

AngularJS Routing with Example

AngularJS routing allows you to build Single Page Applications (SPAs) by routing
different URLs to different views without reloading the entire page.

Example of AngularJS Routing:


```html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Routing Example</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-
route.min.js"></script>
</head>
<body ng-app="myApp">

<a href="/home">Home</a>
<a href="/about">About</a>

<div ng-view></div>

<script>
angular.module('myApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: '

about.html',
controller: 'AboutController'
})
.otherwise({ redirectTo: '/home' });
})
.controller('HomeController', function($scope) {
$scope.message = 'Welcome to the Home Page!';
})
.controller('AboutController', function($scope) {
$scope.message = 'About Us';
});
</script>

</body>
</html>
```
In this example, we use `ngRoute` module to configure routing. Different URLs
(`/home` and `/about`) are mapped to corresponding templates (`home.html` and
`about.html`) and controllers (`HomeController` and `AboutController`). The `ng-
view` directive displays the template based on the current route.

I hope this provides a comprehensive explanation and examples of various concepts in


AngularJS. If you have further questions or need more clarification, feel free to ask!
Unit 4
Certainly! Let's address each of these questions related to Node.js:

Define Node.js

Node.js is an open-source, cross-platform JavaScript runtime environment that


executes JavaScript code outside of a web browser. It uses the V8 JavaScript engine
(developed by Google for Chrome) to execute JavaScript code on the server-side.
Node.js allows developers to build scalable and high-performance applications using
JavaScript.

What is the REPL Terminal in Node.js?

REPL stands for Read Eval Print Loop. The REPL terminal in Node.js is an interactive
environment that allows you to enter JavaScript code and immediately see the results. It
reads input from the user (JavaScript code), evaluates the input, prints the result, and
then loops back to wait for more input. The Node.js REPL terminal is useful for quick
experimentation and testing of JavaScript code snippets.
To start the Node.js REPL terminal, simply open your terminal or command prompt and
type `node`. You will see the `>` prompt indicating that you can start entering
JavaScript commands.

What `setTimeout()` Does in Node.js

In Node.js, the `setTimeout()` function is used to schedule the execution of a function


after a specified delay (in milliseconds). It is part of the Node.js runtime environment
and is used to implement asynchronous behavior.

Syntax:
```javascript
setTimeout(callback, delay, arg1, arg2, ...);
```

- `callback`: The function to be executed after the delay.


- `delay`: The delay (in milliseconds) before executing the callback function.
- `arg1, arg2, ...`: Optional arguments to be passed to the callback function.

Example:
```javascript
// Using setTimeout to execute a function after 2000 milliseconds (2 seconds)
setTimeout(() => {
console.log('2 seconds have passed.');
}, 2000);
```

In this example, the `console.log()` statement inside the callback function will be
executed after a delay of 2000 milliseconds (2 seconds).

I hope this clarifies these concepts related to Node.js. If you have further questions or
need more information, feel free to ask!
Let's address each of these questions related to Node.js:

Differences Between Node.js and JavaScript

1. Environment: Node.js is a runtime environment for executing JavaScript code outside


of a web browser, while JavaScript is a programming language that can be executed in
web browsers.

2. Execution Context: Node.js provides a server-side environment with APIs to interact


with the file system, network, and operating system, while JavaScript in browsers mainly
interacts with the Document Object Model (DOM) and browser APIs.

3. Modules: Node.js uses CommonJS modules (require/export) for modular code


organization, while JavaScript in browsers traditionally used script tags and global
scope for code organization.
4. Core APIs: Node.js provides built-in APIs like `fs` (file system), `http` (HTTP
server/client), `util` (utility functions), etc., which are not available in client-side
JavaScript.

Node.js Web Server

In Node.js, a web server is a server-side program that listens for incoming HTTP
requests from clients (e.g., web browsers) and returns HTTP responses. Node.js can be
used to create web servers using the built-in `http` module.

Example of Node.js Web Server:


```javascript
const http = require('http');

// Create an HTTP server


const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!\n');
});

// Listen on port 3000


server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
```
In this example, we create an HTTP server that listens on port `3000` and responds with
`'Hello World!\n'` for every incoming request.

Module in Node.js

A module in Node.js is a reusable block of code that encapsulates related functionality.


Modules in Node.js can be created using the `module.exports` object to expose
functionality and `require()` function to import functionality into other modules.

Important Core Modules in Node.js:


- `fs` (File System): Provides file system-related APIs (e.g., reading/writing files).
- `http` (HTTP): Provides HTTP server and client functionality.
- `path` (Path): Provides utilities for working with file paths.
- `util` (Utility): Provides various utility functions for debugging and formatting.

REPL Terminal in Node.js

REPL stands for Read Eval Print Loop. The REPL terminal in Node.js is an interactive
environment that allows you to enter JavaScript code, evaluate it, and see the result
immediately.
Four Common REPL Commands:
1. `.help`: Displays a list of available commands and their descriptions.
2. `.break`: Exit from multiline expressions.
3. `.clear`: Clear the current context.
4. `.exit` (or press `Ctrl + C` twice): Exit the REPL terminal.

To start the Node.js REPL terminal, simply open your terminal or command prompt and
type `node`. You will see the `>` prompt indicating that you can start entering
JavaScript commands interactively.

I hope this helps clarify these concepts about Node.js. If you have further questions or
need more information, feel free to ask!
Let's explore each of these topics related to Node.js:

Node.js Process Model

The Node.js process model is single-threaded and event-driven, using a non-blocking


I/O model that makes it efficient for handling concurrent operations. Node.js runs in a
single process and uses an event loop to handle multiple asynchronous operations
without blocking the execution of other tasks.

Blocking and Non-blocking in Node.js

- Blocking: In a blocking operation, the execution of additional JavaScript in the Node.js


process is halted until the operation completes. This can lead to slower performance,
especially in I/O-bound operations.

Example of Blocking:
```javascript
const fs = require('fs');

const data = fs.readFileSync('file.txt'); // Blocking read operation


console.log(data.toString());
console.log('File read operation completed.');
```

- Non-blocking: In a non-blocking operation, the execution of additional JavaScript in


the Node.js process continues while the operation is being performed, without waiting
for it to complete. This allows for better utilization of resources and improved
performance.

Example of Non-blocking:
```javascript
const fs = require('fs');

fs.readFile('file.txt', (err, data) => { // Non-blocking read operation


if (err) throw err;
console.log(data.toString());
});
console.log('File read operation initiated.');
```

HTTP Module in Node.js

The HTTP module in Node.js allows you to create HTTP servers and make HTTP
requests.

Example of HTTP Server:


```javascript
const http = require('http');

// Create an HTTP server


const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World!\n');
});

// Listen on port 3000


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

FS Module in Node.js

The FS (File System) module in Node.js provides file system-related functionality for
reading and writing files.

Example of FS Module:
```javascript
const fs = require('fs');

// Asynchronous file read operation


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

// Synchronous file read operation (blocking)


const data = fs.readFileSync('file.txt');
console.log(data.toString());
```

Synchronous vs. Asynchronous File Handling in Node.js


- Synchronous Approach:
```javascript
const fs = require('fs');

// Synchronous file read operation (blocking)


const data = fs.readFileSync('file.txt');
console.log(data.toString());
```

- Asynchronous Approach:
```javascript
const fs = require('fs');

// Asynchronous file read operation (non-blocking)


fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data.toString());
});
```

URL Module in Node.js

The URL module in Node.js provides utilities for URL resolution and parsing.

Example of URL Module:


```javascript
const url = require('url');

const urlString = 'https://example.com/path?query=value';


const parsedUrl = url.parse(urlString, true);

console.log(parsedUrl.hostname); // Output: example.com


console.log(parsedUrl.pathname); // Output: /path
console.log(parsedUrl.query); // Output: { query: 'value' }
```

Custom/Local Module in Node.js

A custom module in Node.js is a JavaScript file that exports functionalities using


`module.exports` and can be imported into other files using `require()`.

Example of Custom Module:


```javascript
// math.js (custom module)
module.exports.add = (a, b) => {
return a + b;
};

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

Callback Function in Node.js

A callback function in Node.js is a function passed as an argument to another function,


which will be invoked when a specific task is completed.

Example of Callback Function:


```javascript
function fetchData(callback) {
setTimeout(() => {
const data = 'Hello, Node.js!';
callback(data);
}, 2000);
}

fetchData((data) => {
console.log(data); // Output: Hello, Node.js!
});
```

Promises in Node.js

Promises in Node.js provide an alternative approach to handling asynchronous


operations and managing callbacks.

Example of Promises:
```javascript
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = 'Hello, Node.js!';
resolve(data);
}, 2000);
});
}

fetchData()
.then((data) => {
console.log(data); // Output: Hello, Node.js!
})
.catch((err) => {
console.error(err);
});
```

Commonly Used Events in Streams

Some commonly used events in Node.js streams include:


- `data`: Emitted when data is available to be read.
- `end`: Emitted when there is no more data to be read.
- `error`: Emitted when an error occurs.
- `close`: Emitted when the underlying resource is closed.

Example of Stream Event:


```javascript
const fs = require('fs');
const readStream = fs.createReadStream('file.txt');

readStream.on('data', (chunk) => {


console.log(`Received ${chunk.length} bytes of data.`);
});

readStream.on('end', () => {

console.log('End of file.');
});

readStream.on('error', (err) => {


console.error(err);
});
```

These examples and explanations cover various aspects of Node.js programming,


including file handling, HTTP server creation, event handling, and asynchronous
operations. If you have further questions or need more clarification on any topic, feel
free to ask!
Unit 5
Let's dive into these topics related to Express.js:

Express.js Overview

Express.js is a popular web application framework for Node.js. It provides a robust set
of features for building web applications and APIs with Node.js. Express.js simplifies the
process of handling HTTP requests, routing, middleware integration, and more.

Reasons to Choose Express.js for Your Project


1. Minimal and Flexible: Express.js is minimal and unopinionated, allowing developers
to structure their applications as they see fit.
2. Middleware Support: Express.js has a powerful middleware system that enables
adding custom functionalities to the request-response cycle.
3. Routing: It provides a simple and effective way to define routes for handling different
HTTP methods and URL patterns.
4. Extensive Ecosystem: Express.js has a large ecosystem of plugins and middleware,
making it easy to add features like authentication, logging, and more.
5. Performance: Express.js is lightweight and efficient, making it suitable for building
high-performance web applications.

Starting a Server in Express.js (Step-by-Step Example)

To start a server using Express.js, follow these steps:

1. Install Express.js: First, install Express.js using npm if it's not already installed.
```bash
npm install express
```

2. Create an Express Application: Create a new JavaScript file (e.g., `app.js`) and
import Express.
```javascript
const express = require('express');
const app = express();
const port = 3000; // Port number for the server

// Define a route
app.get('/', (req, res) => {
res.send('Hello World!');
});

// Start the server


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

3. Run the Application: Execute the following command to start the Express server.
```bash
node app.js
```

Routing in Express.js (Example)

Routing in Express.js refers to defining endpoints (URLs) and handling different HTTP
methods on those endpoints.
Example of Routing in Express.js:
```javascript
const express = require('express');
const app = express();

// Define a route for handling GET requests


app.get('/students', (req, res) => {
const student = { name: 'John', age: 20, grade: 'A' };
res.json(student);
});

// Start the server


app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
```
In this example, when a `GET` request is made to `/students` URL, the server
responds with a JSON object representing a student.

Express.js Middleware

Middleware in Express.js are functions that have access to the request and response
objects. They can modify these objects, execute additional code, terminate the request-
response cycle, or call the next middleware in the stack.

Example of Middleware in Express.js:


```javascript
const express = require('express');
const app = express();

// Custom middleware
app.use((req, res, next) => {
console.log('Request received at:', new Date());
next(); // Call the next middleware
});

// Route handling
app.get('/', (req, res) => {
res.send('Hello World!');
});

// Start the server


app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
```
In this example, the custom middleware logs the timestamp of each incoming request
before passing control to the next middleware or route handler.

Handling HTML GET Request in Express.js (Example)

To handle an HTML GET request in Express.js, you can define a route that responds with
HTML content.

Example of Handling HTML GET Request:


```javascript
const express = require('express');
const app = express();

// Define a route for handling GET requests


app.get('/hello', (req, res) => {
res.send('<h1>Hello, Express!</h1>');
});

// Start the server


app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
```
In this example, when a `GET` request is made to `/hello` URL, the server responds
with an HTML `<h1>` heading.

These examples demonstrate basic concepts and usage of Express.js for building web
applications and APIs. If you have further questions or need more clarification, feel free
to ask!
Let's cover these topics related to Express.js and MongoDB:

Four Features of Express.js

1. Routing: Express.js provides a robust routing system that allows you to define
endpoints for handling different HTTP methods and URL patterns.
2. Middleware: Express.js has a powerful middleware system that enables adding
custom functionalities to the request-response cycle, such as logging, authentication,
error handling, etc.
3. Template Engines: Express.js supports various template engines (e.g., EJS, Pug) for
generating dynamic HTML content on the server.
4. Error Handling: Express.js simplifies error handling by providing middleware functions
specifically designed for error management and propagation.

Handling HTML GET Request in Express.js (Example)

To handle an HTML GET request in Express.js and respond with HTML content, you can
define a route that sends an HTML response using the `res.send()` method.
Example of Handling HTML GET Request:
```javascript
const express = require('express');
const app = express();

// Define a route for handling GET requests


app.get('/hello', (req, res) => {
res.send('<h1>Hello, Express!</h1>');
});

// Start the server


app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
```
In this example, when a `GET` request is made to `/hello` URL, the server responds
with an HTML `<h1>` heading.

Defining Routes in Express.js and Handling HTTP Methods (GET, POST)

In Express.js, you can define routes using the `app.get()` and `app.post()` methods to
handle `GET` and `POST` HTTP methods, respectively.

Example of Defining Routes and Handling HTTP Methods:


```javascript
const express = require('express');
const app = express();

// Define a route for handling GET requests


app.get('/students', (req, res) => {
// Handle GET request to /students endpoint
res.send('List of students');
});

// Define a route for handling POST requests


app.post('/students', (req, res) => {
// Handle POST request to /students endpoint
res.send('Student created');
});

// Start the server


app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
```
In this example:
- The `GET` request to `/students` responds with "List of students".
- The `POST` request to `/students` responds with "Student created".

Connecting to MongoDB Database Using Node.js

To connect to a MongoDB database using Node.js, you can use the `mongodb`
package along with `mongoose` (a MongoDB object modeling tool).

Steps to Connect to MongoDB Database:


1. Install the `mongoose` package using npm:
```bash
npm install mongoose
```

2. Create a Node.js file and require `mongoose`:


```javascript
const mongoose = require('mongoose');
const dbURI = 'mongodb://localhost/mydatabase'; // MongoDB URI

// Connect to MongoDB
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true });

// Get the default connection


const db = mongoose.connection;

// Event handlers for MongoDB connection


db.on('connected', () => {
console.log('Connected to MongoDB');
});

db.on('error', (err) => {


console.error('MongoDB connection error:', err);
});
```

3. Replace `'mongodb://localhost/mydatabase'` with your MongoDB URI (e.g.,


connection string for your MongoDB server).

4. Start the Node.js application:


```bash
node app.js
```

In this example, we use `mongoose.connect()` to establish a connection to the


MongoDB database specified by the URI. The `mongoose.connection` object provides
event handlers (`'connected'`, `'error'`, etc.) to handle connection-related events.
Unit 6
Let's break down these tasks into two parts: creating a login page using HTML and
Express.js, and developing a simple AngularJS calculator application.

Part A: Create a Login Page Using HTML and Express.js

To create a login page using HTML and Express.js, follow these steps:

1. Set Up Express.js Server:


Create a new Express.js project and set up a basic server.

2. Create HTML Login Form:


Create an HTML file (`login.html`) for the login form.

```html
<!-- login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="/login" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<button type="submit">Login</button>
</form>
</body>
</html>
```

3. Set Up Express.js Routes:


Set up Express.js routes to serve the login page and handle login POST requests.

```javascript
// app.js (Express.js server)
const express = require('express');
const app = express();
const bodyParser = require('body-parser');

// Middleware for parsing URL-encoded request bodies


app.use(bodyParser.urlencoded({ extended: false }));
// Serve the login page
app.get('/login', (req, res) => {
res.sendFile(__dirname + '/login.html');
});

// Handle login POST request


app.post('/login', (req, res) => {
const { username, password } = req.body;
// Validate username and password (for demonstration only)
if (username === 'admin' && password === 'password') {
res.send('Login successful!');
} else {
res.send('Invalid username or password.');
}
});

// Start the server


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

4. Run the Server:


Start the Express.js server by running `node app.js`, and navigate to
`http://localhost:3000/login` in your web browser to access the login page.

Part B: Develop a Simple AngularJS Calculator Application

To develop a simple AngularJS calculator application, follow these steps:

1. Set Up AngularJS Application:


Include AngularJS library in your HTML file (`calculator.html`) and define an AngularJS
module.

```html
<!-- calculator.html -->
<!DOCTYPE html>
<html lang="en" ng-app="CalculatorApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Calculator</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="CalculatorController">
<h2>AngularJS Calculator</h2>
<input type="number" ng-model="operand1">
<input type="number" ng-model="operand2">
<button ng-click="add()">+</button>
<button ng-click="subtract()">-</button>
<button ng-click="multiply()"></button>
<button ng-click="divide()">/</button>
<p>Result: {{ result }}</p>

<script>
angular.module('CalculatorApp', [])
.controller('CalculatorController', function($scope) {
$scope.add = function() {
$scope.result = $scope.operand1 + $scope.operand2;
};

$scope.subtract = function() {
$scope.result = $scope.operand1 - $scope.operand2;
};

$scope.multiply = function() {
$scope.result = $scope.operand1 $scope.operand2;
};

$scope.divide = function() {
$scope.result = $scope.operand1 / $scope.operand2;
};
});
</script>
</body>
</html>
```

2. Run the Calculator Application:


Save the `calculator.html` file and open it in a web browser. You can enter two
numbers in the input fields and click on the arithmetic operation buttons (`+`, `-`, ``,
`/`) to perform calculations.

This example demonstrates how to create a basic AngularJS calculator application that
can perform arithmetic operations based on user input.

You might also like