Angular Lab
Angular Lab
LABORATORY MANUAL
SUBJECT: ANGULAR JS & NODE JS
SEMESTER: V
Institute Mission & Vision
Vision
Development of academically excellent, culturally vibrant, socially
responsible and globally competent human resources.
Mission
To keep pace with advancements in knowledge and make the students
competitive and capable at the global level.
To create an environment for the students to acquire the right physical,
intellectual, emotional and moral foundations and shine as torch
bearers of tomorrow’s society.
To strive to attain ever-higher benchmarks of educational excellence.
2. Problem Analysis: Identify, formulate, research literature, and analyze complex engineering problems
reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering
sciences
Design/development of Solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public health
and safety, and the cultural, societal, and environmental considerations.
4. Conduct Investigations of Complex Problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
5. Modern Tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
7. Environment and Sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
theengineering practice.
9. Individual and Team Work: Function effectively as an individual, and as a member or leader in
diverseteams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
designdocumentation, make effective presentations, and give and receive clear instructions.
11. Project Management and Finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
12. Life-long Learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Department of CS&E, ATMECE, Mysuru.
Angular JS & Node JS – 21CSL581
PSO1: Ability to apply skills in the field of algorithms, database design, web design, cloud computing
and data analytics.
PSO2: Apply knowledge in the field of computer networks for building network and internet-based
applications.
1. Empower students with a strong basis in the mathematical, scientific and engineering
fundamentals to solve computational problems and to prepare them for employment, higher
learning and R&D.
2. Gain technical knowledge, skills and awareness of current technologies of computer science
engineering and to develop an ability to design and provide novel engineering solutions for
software/hardware problems through entrepreneurial skills.
Teaching-Learning Process Chalk and board, Active Learning, practical based learning
Course Outcomes (Course Skill Set)
At the end of the course the student will be able to:
CO 1. Describe the features of Angular JS.
CO 2. Recognize the form validations and controls.
CO 3. Implement Directives and Controllers.
CO 4. Evaluate and create database for simple application.
CO 5. Plan and build webservers with node using Node .JS.
Assessment Details (both CIE and SEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam
(SEE) is 50%. The minimum passing mark for the CIE is 40% of the maximum marks (20
marks). A student shall be deemed to have satisfied the academic requirements and earned the
credits allotted to each course. The student has to secure not less than 35% (18 Marks out of 50)
in the semester-end examination (SEE). The student has to secure a minimum of 40% (40 marks
out of 100) in the sum total of the CIE (Continuous Internal Evaluation) and SEE (Semester End
Examination) taken together.
The Correlation of Course Outcomes (CO’s) and Program Specific Outcomes (PSO’s)
Angular JS Features
Directive Description
ng-app It defines the root element of an application.
ng-bind- It specifies that the text content should be replaced with a template.
template
ng-class-even It is same as ng-class, but will only take effect on even rows.
ng-class-odd It is same as ng-class, but will only take effect on odd rows.
CUSTOM DIRECTIVES
In AngularJS, custom directives are a way to extend the functionality of HTML by creating
your own reusable HTML elements or attributes. Custom directives enable you to encapsulate
complex behaviors and encapsulate them into a single, reusable component. They are a
fundamental building block for creating dynamic and interactive web applications.
Creating a custom directive in AngularJS involves using the directive function of an AngularJS
module. Here's a general outline of how to create a custom directive (Method 1 – inline
template):
1. Define an AngularJS Module: First, create an AngularJS module using the
angular.module function. This module serves as the container for your custom
directive.
2. Create the Directive: Use the directive method on your module to create the directive.
This method takes the name of the directive and a factory function as arguments.
3. Directive Factory Function: The factory function defines the behavior and appearance
of the custom directive. It returns an object with specific properties and methods, such
as restrict (to define how the directive can be used), template (to specify the HTML
template), and link functions (to define behavior).
4. Use the Directive: In your HTML, you can now use your custom directive by its name
as an HTML element or attribute.
Interacting with Server
A Content Delivery Network (CDN) is a network of distributed servers located in various data
centers around the world. CDNs are designed to deliver web content, such as images, videos,
scripts, and other static assets, to users with high availability and performance. They work by
caching content on multiple servers and serving it from the server that is geographically closest
to the user, reducing latency and improving page load times.
In the below program, a CDN is used to load the AngularJS library into your web page. Here's
where it is used:
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
In this line, you include the AngularJS library by specifying its source URL. This URL points
to a file on Google's CDN that hosts the AngularJS library. When a user opens your web page,
their browser fetches AngularJS from the CDN server closest to their location, which can
significantly speed up the loading of the library.
MODULE 1
Introduction to Angular JS: Introduction – Features – Angular JS Model-View-Controller –
Expression -Directives and Controllers.
Program 1:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Getting Started with AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
<h1>Welcome to AngularJS!</h1>
<p>Dynamic Content Binding Example:</p>
<p>Enter your name: <input type="text" ng-model="name"></p>
<p>Hello, {{ name }}!</p>
</div>
<script>
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
// Initialize scope variables
$scope.name = "User";
});
</script>
</body>
</html>
Explanation:
In this code,
1) We have a simple HTML page that uses AngularJS to demonstrate dynamic content
binding. The ng-app attribute defines the AngularJS application module, and the ng-
controller attribute defines a controller called MyCtrl.
2) The controller initializes a variable name in the scope, and the value is bound to an
input field and displayed dynamically on the page.
3) When you type your name in the input field, it updates the greeting message below.
4) This is a fundamental example to showcase AngularJS's ability to bind data and create
dynamic interactions in web applications.
Output:
Code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
<h1>Simple To-Do List with AngularJS</h1>
</ul>
<script>
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
// Initialize an empty array for tasks
$scope.tasks = [];
$scope.tasks.push($scope.newTask);
$scope.newTask = ''; // Clear the input field
}
};
});
</script>
</body>
</html>
Explanation:
In this example, we create a simple to-do list application:
1. The to-do list is displayed using the ng-repeat directive, which iterates over the tasks
and displays them in an unordered list.
2. An input field and a button allow users to add new tasks to the list. The ng-model
directive binds the input field to the newTask variable.
3. The addTask function is called when the "Add Task" button is clicked. It adds a new
task to the list and clears the input field.
This program serves as a hands-on example for beginners to understand how AngularJS enables
dynamic content binding, making it easy to create interactive web applications.
Students can interact with the to-do list, add tasks, and see how the content updates
dynamically.
Output:
Program 2:
A) Create a basic AngularJS application to build a simple number calculator (build a
calculator that can perform addition and subtraction)
Code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
</head>
<body>
<div ng-controller="CalculatorCtrl">
<h1>Number Calculator with AngularJS</h1>
<p>Enter a number:</p>
</div>
<script>
angular.module('myApp', [])
.controller('CalculatorCtrl', function($scope) {
$scope.number1 = 0;
$scope.number2 = 0;
});
</script>
</body>
</html>
Department of CS&E, ATMECE, Mysuru.
Angular JS & Node JS – 21CSL581
Explanation:
In this program, we:
1. Create a simple calculator that allows you to enter two numbers using input fields with
ng-model.
You can enter numbers in the input fields, and the program will instantly display the results of
addition and subtraction. This example illustrates how AngularJS can be used for simple
calculations and dynamic content updates on a web page.
Output:
B) Create a simple web page that utilizes various AngularJS directives to enhance its
functionality and create controllers to manage the application's behavior.
Code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
</div>
<script>
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
$scope.showContent = true;
};
});
</script>
</body>
</html>
Explanation:
In this code, we explore various AngularJS features:
1. Using ng-if Directive: We conditionally display content based on the value of the
showContent variable.
2. Using ng-repeat Directive: We use the ng-repeat directive to iterate over a list and
display each item in an unordered list.
This code provides a basic example of how to utilize AngularJS directives and controllers to
enhance the functionality of a web page. Students can use this as a starting point to explore
these features in more detail.
Output:
MODULE 2
Angular JS Modules: Arrays –Working with ng-model – Working with Forms – Form
Validation – Error Handling with Forms – Nested Forms with ng-form – Other Form Controls.
Program 3
A simple AngularJS program that demonstrates basic filtering and searching in a "List
of Countries" application.
Code:
<!DOCTYPE html>
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<body>
<div ng-controller="myCtrl">
<h2>List of Countries</h2>
<ul>
<li ng-repeat="country in countries | filter: searchText">
{{ country }}
</li>
</ul>
</div>
<script>
$scope.countries = [
"INDIA",
"Canada",
"Australia",
Department of CS&E, ATMECE, Mysuru.
Angular JS & Node JS – 21CSL581
"United Kingdom",
"Germany",
"France",
"Japan",
"China",
"USA",
"Brazil",
];
$scope.searchText = "";
});
</script>
</body>
</html>
Output:
Explanation:
In this "List of Countries" application:
• The ng-model is used to bind the input field to the searchText variable. Users can
enter text in the input field to filter and search for countries.
• The ng-repeat directive is used to iterate through the countries array and display the
countries. The filter filter is applied to the list to dynamically filter and display
countries based on the value in the searchText variable.
This program is a simple example for learners to understand basic filtering and searching in
AngularJS. Users can search for countries in the list by entering text in the search input field.
Program 4
Write a program that conditionally display different HTML content based on the value
of a variable.
Code:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="">
Choose your favorite topic:
<select ng-model="myVar">
<option value="animals">Zoology
<option value="tuts">Tutorials
<option value="cars">Cars
<option value="bikes">Bikes
</select>
<hr>
<div ng-switch="myVar">
<div ng-switch-when="animals">
<h1>Zoology</h1>
<div ng-switch-when="tuts">
<h1>Tutorials</h1>
<div ng-switch-when="cars">
<h1>Cars</h1>
<div ng-switch-when="bikes">
<h1>bikes</h1>
</div>
<div ng-switch-default>
<h1>Switch</h1>
<p>Select topic from the dropdown, to switch the content of this DIV.</p>
</div>
</div>
<hr>
<p>The ng-switch directive hides and shows HTML sections depending on a certain
value.</p>
</body>
</html>
Explanation:
This program introduces the concept of using the AngularJS ng-switch directive, which allows
you to conditionally display different HTML content based on the value of a variable (myVar).
Let's focus on the new concepts introduced compared to the previous two programs:
• The ng-model directive is used to bind the selected option to a variable (myVar),
which will control the content displayed based on the selected option.
2. ng-switch Directive:
• The <div> element with the ng-switch directive is used to define a container for
content that will be conditionally displayed based on the value of myVar.
3. ng-switch-when Directive:
• Inside the ng-switch container, there are multiple <div> elements, each with the
ng-switch-when directive. These elements specify different values of myVar for
which specific content should be displayed.
4. ng-switch-default Directive:
5. Conditional Content:
The content within each <div> element is conditionally displayed based on the value of
myVar. For example, when myVar is "tuts," the content under <div ng-switch-
when="tuts"> is displayed.
6. Interactivity:
The user can choose their favorite topic from the dropdown menu. Depending on the
selected topic, the content displayed on the page changes dynamically.
7. <hr> Elements:
The program also includes horizontal rule (<hr>) elements to separate different sections
of content.
In summary, this program demonstrates how to use the ng-switch directive in AngularJS to
create conditional content based on the value of a variable (myVar). It allows you to
dynamically switch and display different sections of content on the web page based on user
selections from the dropdown menu.
Output:
MODULE 3
Directives & Building Databases: Part I- Filters – Using Filters in Controllers and Services –
Angular JS Services – Internal Angular JS Services – Custom Angular JS Services
Program 5
Build a simple text transformation application that allows users to convert text touppercase and lowercase
Code:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<body ng-app="textApp">
<div ng-controller="TextController">
<h2>Text Transformer</h2>
<input type="text" ng-model="inputText" placeholder="Enter Text">
<button ng-click="transformToUppercase()">To Uppercase</button>
<button ng-click="transformToLowercase()">To Lowercase</button>
<script>
var app = angular.module('textApp', []);
this.toLowercase = function(input) {
return input.toLowerCase();
};
});
$scope.transformToUppercase = function() {
$scope.transformedText = TextService.toUppercase($scope.inputText);
};
$scope.transformToLowercase = function() {
$scope.transformedText = TextService.toLowercase($scope.inputText);
};
});
</script>
</body>
</html>
Explanation:
In this program:
• We have a text transformation application that allows users to input text.
• We use a custom service, TextService, to transform the text to uppercase and lowercase.
• The TextController handles user interactions and displays the transformed text.
This program demonstrates the use of filters, controllers, and services in the context of a text
transformation application. Users can enter text, and it can be transformed to uppercase or
lowercase.
Output:
Program 6
Build a basic currency converter application that allows users to convert amounts from
one currency to another using a simple exchange rate.
Code:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<body ng-app="currencyConverterApp">
<div ng-controller="CurrencyConverterController">
<h2>Currency Converter</h2>
<input type="number" ng-model="amount" placeholder="Enter Amount">
<select ng-model="fromCurrency" ng-options="currency for currency in currencies">
</select>
<span> to </span>
<select ng-model="toCurrency" ng-options="currency for currency in currencies">
</select>
<button ng-click="convertCurrency()">Convert</button>
<script>
var app = angular.module('currencyConverterApp', []);
USD: 1.18,
GBP: 0.88,
JPY: 131.34
},
GBP: {
INR: 92.90,
USD: 1.35,
EUR: 1.14,
JPY: 148.37
},
JPY: {
INR: 0.63,
USD: 0.0090,
EUR: 0.0076,
GBP: 0.0067
}
};
app.controller('CurrencyConverterController', function($scope,
CurrencyConverterService) {
$scope.amount = 1;
$scope.fromCurrency = 'INR'; // Set INR as the default source currency
$scope.toCurrency = 'USD';
$scope.currencies = ['INR', 'USD', 'EUR', 'GBP', 'JPY']; // Add INR as the first item
$scope.convertedAmount = 0;
$scope.convertCurrency = function() {
$scope.convertedAmount = CurrencyConverterService.convert($scope.amount,
$scope.fromCurrency, $scope.toCurrency);
};
});
</script>
</body>
</html>
Explanation:
• We have a currency converter application that allows users to input an amount and
select the source and target currencies.
This program demonstrates the use of filters, controllers, and services in the context of a
currency conversion application. Users can enter an amount and select source and target
currencies, and the converted amount is displayed based on predefined exchange rates.
Output:
MODULE-4
Directives & Building Databases: Part-II- Directives – Alternatives to Custom Directives –
Understanding the Basic options – Interacting with Server –HTTP Services – Building
Database, Front End and BackEnd
Program 7
Create a simple AngularJS application with a custom directive for displaying and
interacting with a list of fruits.
Code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<style>
</style>
</head>
<body ng-controller="MainController">
<dynamic-list items="fruits"></dynamic-list>
<script>
angular.module('myApp', [])
.directive('dynamicList', function () {
return {
restrict: 'E',
scope: {
items: '='
},
template: `
<ul>
{{ item }}
</li>
</ul>
`,
link: function (scope, element, attrs) {
scope.selectItem = function (item) {
};
}
};
})
.controller('MainController', function ($scope) {
</script>
</body>
</html>
Explanation:
1. AngularJS Setup:
<html ng-app="myApp">: This sets up an AngularJS application by declaring the
ng-app directive on the <html> element. The application is named "myApp."
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></scri
pt>: This includes the AngularJS library from a CDN, making AngularJS available
for the application.
<style>: This defines some basic CSS styles used for the list.
2. AngularJS Module and Directive:
angular.module('myApp', []): Here, we create an AngularJS module named
"myApp" using the angular.module function. This module serves as the container for
the application.
.directive('dynamicList', function () { ... }: We define a custom directive named
"dynamic-list." This directive restricts it to be used as an element ('E').
3. Directive Template:
The template property in the directive definition provides the HTML template for the
In summary, this program creates a simple AngularJS application with a custom directive for
displaying and interacting with a list of fruits. The custom directive makes it easy to create
reusable components within your application, enhancing the modularity and maintainability
of your code.
Output:
Program 8:
A simple AngularJS program that demonstrates the basic CRUD (Create, Read, Update,
Delete) operations using mock data.
Code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Simple CRUD App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="MainController">
<h1>Simple CRUD App</h1>
<script>
var app = angular.module('myApp', []);
$scope.newItem = '';
$scope.isEditing = false;
$scope.editedItem = '';
$scope.addItem = function () {
if ($scope.newItem) {
$scope.items.push($scope.newItem);
$scope.newItem = '';
}
};
$scope.saveEdit = function () {
if ($scope.editedItem) {
$scope.items[$scope.editedItemIndex] = $scope.editedItem;
$scope.isEditing = false;
$scope.editedItem = '';
}
};
$scope.cancelEdit = function () {
$scope.isEditing = false;
$scope.editedItem = '';
};
Explanation:
In this example, we have a simple web page with a list of items, and you can perform the
following CRUD operations:
This is a basic AngularJS application that demonstrates the principles of CRUD operations
using mock data.
Output:
Note:
In this example, we won't use a real backend or a database, but we'll simulate data
manipulation within the AngularJS application.
In a real-world application, you would replace the mock data with data fetched from a
server and implement API calls for actual database interactions.
MODULE-5
Introduction to NODE .JS: Introduction –Using the Terminals – Editors –Building a Webserver
with Node – The HTTP Module – Views and Layouts.
Introduction:
Editors
• To write Node.js code, you'll need a text editor or an integrated development
environment (IDE). Some popular choices for writing Node.js code include Visual
Studio Code, Sublime Text, and Atom. These editors provide features like syntax
highlighting, code completion, and debugging tools to make your coding process more
efficient.
Difference Between Node JS and Angular JS
Node.js and AngularJS are two distinct technologies used in web development, but they serve
different purposes and have different roles in a web application.
Node.js AngularJS
Type Node.js is a runtime environment AngularJS (often referred to as
for executing JavaScript code on the "Angular 1") is a JavaScript
server-side. framework for building dynamic web
applications on the client-side.
Department of CS&E, ATMECE, Mysuru.
Angular JS & Node JS – 21CSL581
Use Case: Node.js: It is typically used for AngularJS: It is used on the client-side
server-side programming, enabling to build dynamic, single-page web
the creation of server applications applications (SPAs). AngularJS
and APIs. It's well-suited for provides a framework for creating the
building web servers, real-time user interface and handling client-side
applications, and microservices. application logic.
Note: Replace myprogram.js with the actual name of your JavaScript file.
Sample Program:
Write a simple Node.js program that reads a text file and prints its contents to the console.
Description: You can create a text file with some content in the same directory as this script
and then run it to see the contents of the file displayed in the console.
Step 1: Create a text file named sample.txt with some text content. For example, you can
create a file with the following text:
Hello, Node.js!
Step 2: Create a Node.js program, let's name it readFile.js, with the following code:
readFile.js
Step 3: Open your terminal or command prompt, navigate to the directory where both
sample.txt and readFile.js are located, and run the Node.js program:
node readFile.js
Output:
Program 9:
A simple Node.js program that creates a basic HTTP server and responds with "Hello,
Node.js!" when you access it through a web browser.
Step 1: Create a new JavaScript file, let's call it simpleServer.js, with the following code.
Code:
// Import the 'http' module
const http = require('http');
Step 2: Open your terminal or command prompt, navigate to the directory where
simpleServer.js is located, and run the Node.js program.
node simpleServer.js
Output:
You should see the message "Server is running at http://localhost:3000/" in the terminal,
indicating that the server is running.
Now, open a web browser and visit http://localhost:3000/. You should see a simple webpage
displaying "Hello, Node.js!" in your browser.
Note: You can stop the server by pressing Ctrl + C in your terminal.
1. Setting Up Node.js: First, make sure you have Node.js installed. If not, you can
download it from the official website: https://nodejs.org.
2. Creating a Server: To create a web server in Node.js, you typically use the built-in
http module. However, many developers prefer using Express.js, a web application
framework that simplifies server creation and routing.
3. Handling HTTP Requests: Define routes to handle various HTTP requests (GET,
POST, PUT, DELETE, etc.) from clients. These routes are associated with specific
URL paths and define how your server responds to different requests.
4. Serving Content: You can serve HTML, JSON, static files (like CSS and images), and
more. You set the appropriate response headers and send the content back to the client.
Program 10
Write a program which demonstrates the basic concept of building a web server with
Node.js using Express.js.
Description: This example demonstrates the basic concept of building a web server with
Node.js using Express.js. You can expand this server by defining more routes, serving HTML
pages, handling POST requests, and building more complex web applications.
Install Express.js if you haven't already by running “npm install express” in your project
directory.
Step 1:
1. Install Express.js if you haven't already by running npm install express in your
project directory.
Note: You should ensure that “npm” operates within a directory where you have the
necessary permissions (Preferably other than C Drive).
2. Create a JavaScript file, let's call it webServer.js, and add the following code:
const express = require('express');
const app = express();
const port = 3000;
});
// Start the server
app.listen(port, () => {
Explanation:
In this code:
Step 3: Open your terminal, navigate to the directory where webServer.js is located,
and run the Node.js program.
node webServer.js
You should see the message "Server is running on http://localhost:3000" in the terminal.
Open a web browser and visit http://localhost:3000/. You'll see the text "Hello, this is your
Node.js web server!" displayed in your browser.
Output:
Program 11:
Write an application-oriented Node.js program that fetches data from a public API and
displays it in your console.
Note: In this example, we'll use the JSONP laceholder API to retrieve a list of posts.
Step 1: First, make sure you have Node.js installed on your system. If you don't have it, you
can download it from the official website: https://nodejs.org.
Step 2: Create a new JavaScript file, let's call it fetchPosts.js, and add the following code:
const axios = require('axios');
console.log('List of Posts:');
posts.forEach((post) => {
console.log(`Title: ${post.title}`);
console.log(`Body: ${post.body}\n`);
});
} catch (error) {
In this code:
• We use the Axios library to make an HTTP GET request to the JSONPlaceholder API
(https://jsonplaceholder.typicode.com/posts) to retrieve a list of posts.
• The fetchPosts function is an asynchronous function that fetches the data and displays
the titles and bodies of the posts in the console.
Step 3: Navigate to the directory where your Node.js program (in this case, fetchPosts.js) is
located. You should run the following commands from the directory where your JavaScript
file is. Run the following command to install 'axios':
Step 4: After the installation is complete, you can run your Node.js program again using the
following command:
node fetchPosts.js
Output:
HTTP Module:
The HTTP module in Node.js allows you to create HTTP servers and handle HTTP requests.
It provides functions for handling HTTP requests and responses. Using the HTTP module, you
can create a web server that listens for incoming HTTP requests and responds to them.
Program 5:
Write a simple example of creating an HTTP server using the HTTP module in Node.js
Code:
const http = require('http');
});
Explanation:
In this code:
1. We import the HTTP module using const http = require('http').
5. We specify the port and host on which the server will listen. In this case, it's listening
on port 3000 and the local host ('127.0.0.1').
6. Finally, we start the server using server.listen. The callback function logs a message
to the console when the server starts.
Output:
To run this program, save it to a JavaScript file (e.g., httpServer.js) and execute it using the
node command:
node httpServer.js
Program 12
Write a simple program that illustrates the use of views and layouts in a Node.js
application using the EJS templating engine.
Step 1: First, make sure you have Node.js installed on your system. If you don't have it, you
can download it from the official website: https://nodejs.org.
Step 2: Create a new directory for your project and navigate to it in your terminal.
Step 3: Initialize a new Node.js project and install the required dependencies. Run the
following commands:
npm init -y
npm install express ejs
Step 4: Create a new file, app.js, and add the following code:
const express = require('express');
const app = express();
Inside the views directory, create an EJS template file named index.ejs with the
following content:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<header>
<main>
<p>This is the main content of the page.</p>
</main>
<footer>
<p>© 2023 My Website</p>
</footer>
</body>
</html>
Explanation:
In this program:
• We use Express.js as the web framework.
• We set the view engine to EJS using app.set('view engine', 'ejs').
• There's a single route that renders the index.ejs view and passes a title variable to it.
• The index.ejs view is an EJS template that includes placeholders (<%= title %>) for
dynamic data. The title variable is passed from the route.
• When you access the root URL (http://localhost:3000), the EJS template is rendered,
and the dynamic title is displayed.
Step 6: To See the output
Open a web browser and navigate to http://localhost:3000 to see the rendered view with
a layout. The layout includes a header and footer, and the content is dynamically
populated with the title provided in the route.
Output: