0% found this document useful (0 votes)
30 views21 pages

WT Practicals ALL

This document provides examples of using various Node.js modules and core concepts. It demonstrates the OS and PATH modules, built-in modules like FS and HTTP, event-driven programming using EventEmitter, and file handling operations using the FS module both synchronously and asynchronously. It also shows how to create and export functions from modules, require modules in other files, and build a simple event emitter.

Uploaded by

vishalwilp2021
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)
30 views21 pages

WT Practicals ALL

This document provides examples of using various Node.js modules and core concepts. It demonstrates the OS and PATH modules, built-in modules like FS and HTTP, event-driven programming using EventEmitter, and file handling operations using the FS module both synchronously and asynchronously. It also shows how to create and export functions from modules, require modules in other files, and build a simple event emitter.

Uploaded by

vishalwilp2021
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/ 21

PRACTICAL 1: What is node js Demonstrate OS and PATH module

Node is an environment in which you can run JavaScript code "Outside the web browser".
These are basically variables which store some data and can be accessed from anywhere in
your code – doesn't matter how deeply nested the code is.
Commonly used Global variables:
• __dirname: This variable stores the path to the current working directory.
• __filename: This variable stores the path to the current working file.
Create a new file called app.js and open up a new integrated VS Code Terminal.
Paste the following code in the app.js file and save it:
// __dirname Global Variable
console.log(__dirname);

// __filename Global Variable


console.log(__filename);
To run this code using Node, type in the following command in the terminal and press
Enter: node app.js.

Modules in NodeJS

In Node.js, a module is essentially a reusable block of code that can be used to perform a
specific set of tasks or provide a specific functionality. A module can contain variables,
functions, classes, objects, or any other code that can be used to accomplish a particular task
or set of tasks.
This is the code in hello.js file:
function sayHello(name){
console.log(`Hello ${name}`);
}

module.exports = sayHello
This is the code in app.js file:
const sayHello = require('./hello.js');

sayHello('John');
sayHello('Peter');
sayHello('Rohit');
The file hello.js can be called the module in this case. Every module has an object
called exports which should contain all the stuff you want to export from this module like
variables or functions. In our case, we are defining a function in the hello.js file and directly
exporting it.
The app.js file imports the sayHello() function from hello.js and stores it in
the sayHello variable. To import something from a module, we use the require() method
which accepts the path to the module. Now we can simply invoke the variable and pass a
name as a parameter. Running the code in app.js file will produce the following output:
Hello John
Hello Peter
Hello Rohit
Built In modules in Nodejs

The OS Module
The OS Module (as its name implies) provides you methods/functions with which you can
get information about your Operating System.
const os = require('os')

// os.uptime()
const systemUptime = os.uptime();

// os.userInfo()
const userInfo = os.userInfo();

// We will store some other information about my WindowsOS in this object:


const otherInfo = {
name: os.type(),
release: os.release(),
totalMem: os.totalmem(),
freeMem: os.freemem(),
}

// Let's Check The Results:


console.log(systemUptime);
console.log(userInfo);
console.log(otherInfo);

The PATH Module


The PATH module comes in handy while working with file and directory paths. It provides
you with various methods with which you can:
• Join path segments together

• Tell if a path is absolute or not

• Get the last portion/segment of a path


• Get the file extension from a path,etc

// Import 'path' module using the 'require()' method:


const path = require('path')

// Assigning a path to the myPath variable


const myPath = '/mnt/c/Desktop/NodeJSTut/app.js'

const pathInfo = {
fileName: path.basename(myPath),
folderName: path.dirname(myPath),
fileExtension: path.extname(myPath),
absoluteOrNot: path.isAbsolute(myPath),
detailInfo: path.parse(myPath),
}

// Let's See The Results:


console.log(pathInfo);
PRACTICAL 2: Demonstrate HTTP module
The FS Module
This module helps you with file handling operations such as:
• Reading a file (sync or async way)

• Writing to a file (sync or async way)

• Deleting a file

• Reading the contents of a director

• Renaming a file

• Watching for changes in a file, and much more

// Import fs module
const fs = require('fs');

// Present Working Directory: C:\Desktop\NodeJSTut


// Making a new directory called ./myFolder:

fs.mkdir('./myFolder', (err) => {


if(err){
console.log(err);
} else{
console.log('Folder Created Successfully');
}
})
create and write to a file asynchronously

const fs = require('fs');

const data = 'Hi,this is newFile.txt';

fs.writeFile('./myFolder/myFile.txt', data, {flag: 'a'}, (err) => {


if(err){
console.log(err);
return;
} else {
console.log('Writen to file successfully!');
}
})
read a file asynchronously
const fs = require('fs');

fs.readFile('./myFolder/myFile.txt', {encoding: 'utf-8'}, (err, data) => {


if(err){
console.log(err);
return;
} else {
console.log('File read successfully! Here is the data');
console.log(data);
}
})
Reading and Writing to a File Synchronously
const fs = require('fs');

try{
// Write to file synchronously
fs.writeFileSync('./myFolder/myFileSync.txt', 'myFileSync says Hi');
console.log('Write operation successful');

// Read file synchronously


const fileData = fs.readFileSync('./myFolder/myFileSync.txt', 'utf-8');
console.log('Read operation successful. Here is the data:');
console.log(fileData);

} catch(err){
console.log('Error occurred!');
console.log(err);
}

To implement Event Driven Programming in NodeJS, You need to remember 2 things:


• There is a function called emit() which causes an event to occur.
For example, emit('myEvent') emits/causes an event called myEvent.
• There is another function called on() which is used to listen for a particular event and
when this event occurs, the on() method executes a listener function in response to it

// Importing 'events' module and creating an instance of the EventEmitter Class


const EventEmitter = require('events');
const myEmitter = new EventEmitter();

// Listener Function - welcomeUser()


const welcomeUser = () => {
console.log('Hi There, Welcome to the server!');
}

// Listening for the userJoined event using the on() method


myEmitter.on('userJoined', welcomeUser);

// Emitting the userJoined event using the emit() method


myEmitter.emit('userJoined');
PRACTICAL 3A
Write a simple program for multiplication USING ANGULARJS
<html>
<head>
<title>AngularJS Application</title>
</head>

<body ng-app>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js">
</script>
<h1>Sample Application</h1>
Enter Numbers to Multiply:
<input type="text" ng-model="Num1" /> x <input
type="text" ng-model="Num2" />
= <span>{{Num1 * Num2}}</span>
</body>
</html>

PRACTICAL 3B:
Write a program to display your name with welcome note :HELLO
><!doctype html>
<html ng-app>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</script>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name
here">
<h1>Hello {{yourName}}!</h1>
</div>
</body>
</html>
PRACTICAL 4A: Demonstarte controllers in angularjs
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">


{{ firstName + " " + lastName }}
</div>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>

4B: A controller can also have methods:


<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="exampleController">


First Name: <input type="text" ng-model="FirstName"><br>
Last Name: <input type="text" ng-model="LastName"><br>
<br>
Full Name: {{FullName()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('exampleController', function($scope) {
$scope.FirstName = "John";
$scope.LastName = "Doe";
$scope.FullName = function() {
return $scope.FirstName + " " + $scope.LastName;
};
});
</script>
</body>
</html>
4C: Nested Controllers
<!DOCTYPE html>
<html>
<head>
<title>AngualrJS Controller</title>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myNgApp">
<div ng-controller="parentController">
Message: {{message1}}
<div ng-controller="childController">
Parent Message: {{message1}} </br>
Child Message: {{message2}}
</div>
Child Message: {{message2}}
</div>
<script>
var ngApp = angular.module('myNgApp', []);
ngApp.controller('parentController', function ($scope) {
$scope.message1 = "This is parentController";
});
ngApp.controller('childController', function ($scope) {
$scope.message2 = "This is childController";
});
</script>
</body>
</html>
Practical 5:
5ADemonstarte the various ng-directives in AngularJS
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
<body>

<div ng-app="" ng-init="firstName='John'">

<p>Input something in the input box:</p>


<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>

</div>

</body>
</html>

5B Repeating HTML Elements

The ng-repeat directive repeats an HTML element:


<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
<body>

<div ng-app="" ng-init="names=['Jani','Hege','Kai']">


<p>Looping with ng-repeat:</p>
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>

</body>
</html>

5CConditional directive
<!DOCTYPE html>

<html>
<head>
<title>
AngularJs ng-if Directive Example</title>
<script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"> </script>
<script>
var app = angular.module("AngularngifApp", []);
app.controller("ngifctrl", function ($scope) {
$scope.items = ['one', 'two', 'three', 'four'];
$scope.selectval = "two";
});

</script>
</head>
<body ng-app="AngularngifApp">
<div ng-controller="ngifctrl">
Select Item: <select ng-model="selectval" ng-options="x for x in items">
</select>
<p> You have selected <span ng-bind="selectval"</span></p>
<br /><br />
<div ng-if="selectval=='one'">
<b>Show Div If Selected Value One</b>
</div>
</div>
<input type="checkbox" ng-model="showDiv" />
<label for="showDiv"> Check it </label>
<br><br>
<div class="nk" ng-if="showDiv">
hello stduents good mroning
</div>

</body>
</html>

5DAngularJs ng-style Directive Example

<!DOCTYPE html>
<html >
<head>
<title>ng-style</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
<style type="text/css">
.bg-color {
background-color: orange;
}
</style>
</head>
<body ng-app="app">
<h1 ng-controller="myCtrl" ng-style="myObj">Welcome</h1>
<div ng-controller="controllerName">
<input type="text" ng-model="color" placeholder="Enter any color." />
<p ng-repeat="record in records" ng-style="{color:color}">
<span class="bg-color"> Name: {{record.name}}</span>
</p>
</div>
<script>
var app = angular.module("app", []);
app.controller('controllerName', ['$scope', function ($scope) {
$scope.records = [{ name: 'Java Script' }, { name: 'AngularJS' }, { name: 'Jquery' }, {
name: 'Bootstrap' }];

}]);
app.controller("myCtrl", function($scope) {
$scope.myObj = {
"color" : "white",
"background-color" : "coral",
"font-size" : "60px",
"padding" : "50px"
}
});
</script>
</body>
</html>

5EMouse events directive

<!DOCTYPE html>
<html >
<head>
<title>ng-click</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
</head>
<body ng-app="clickExample">
<div ng-controller="ExampleController">
<a href="# ng-click="showAlert()">Click Here </a>
</div>
<script>
var app = angular.module("clickExample", []);
app.controller('ExampleController', ['$scope', function ($scope) {
$scope.showAlert = function () {
alert("This is an example of ng-click");
}
}]);
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>ng-mouseover</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
<style>
.nav {
padding: 10px;
cursor: pointer;
background-color: gray;
border-bottom: 5px solid tomato;
}
</style>
</head>
<body ng-app="app">
<div ng-controller="controllerName">
<span class="nav" ng-repeat="p in nav" ng-style="style" ng-
mouseover="style={'border-bottom': '5px solid red','background-
color':'pink','cursor':'pointer'}" ng-mouseleave="style={}">{{p}}</span>
</div>
<script>
var app = angular.module("app", []);
app.controller('controllerName', ['$scope', function ($scope) {
$scope.nav=["Home","About","Contact"]
}]);
</script>

</body>
</html>

5F Keyboard directives
<!DOCTYPE html>
<html >
<head>
<title>ng-keyup</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
</head>
<body ng-app>
<div>
Type in text box to update count value.<br />
<input type="text" ng-init="count=0" ng-keyup="count=count+1" /><br />
Count:{{count}}
</div>
</body>
</html>
PRACTICAL 6:
Demonstrate Input Validation features of Angular.js forms with a
program
Input fields have the following states:
• $untouched The field has not been touched yet
• $touched The field has been touched
• $pristine The field has not been modified yet
• $dirty The field has been modified
• $invalid The field content is not valid
• $valid The field content is valid
They are all properties of the input field, and are either true or false.
Form State:
Forms have the following states:
• $pristine No fields have been modified yet
• $dirty One or more have been modified
• $invalid The form content is not valid
• $valid The form content is valid
• $submitted The form is submitted

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Welcome in the Angular JS</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
</head>
<body ng-app>
<div>
<form name="sampleForm">
<input type="text" ng-model="name" name="name" required />
<span ng-show="sampleForm.name.$error.required" class="text-danger">This field is
required !</span><br />

Form Valid : {{sampleForm.$valid}} <br />


Form Invalid : {{sampleForm.$invalid}} <br />

Input Valid : {{sampleForm.name.$valid}} <br />


Input Invalid : {{sampleForm.name.$invalid}} <br />

Required Error : {{sampleForm.name.$error.required}} <br />

dirty : {{sampleForm.name.$dirty}} <br />


pristine : {{sampleForm.name.$pristine}} <br />
</form>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>

<body ng-app="formApp" ng-controller="formCtrl">


<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"
></script>
<script>
var app = angular.module('formApp', []);
app.controller('formCtrl', function ($scope) {
$scope.sendForm = function () {
$scope.msg='Form Submited Successfully';
};
$scope.getClass = function (color) {
return color.toString();
}
});
</script>
<h3>AngularJS Form Input Fields Validation</h3>
<form name="personForm" ng-submit="sendForm()">
<label for="name">Name</label>
<input id="name" name="name" type="text" ng-model="person.name"
required />
<span class="error" ng-show="personForm.name.$error.required">
Required!!! </span>
<br /><br />
<label for="address">address</label>
<input id="address" name="address" type="text" ng-model="person.address"
required />
<span class="error" ng-show="personForm.address.$error.required"> address Required!!!
</span>
<br /><br />
<label for="mobile">contact no.</label>
<input id="mobile" name="mobile" type="number" ng-model="person.mobile" ng-
minlength="10" ng-maxlength="10"
required />
<span class="error" ng-show="personForm.mobile.$error.required"> mobile Required!!!
</span>
<span class="error" ng-show="(personForm.mobile.$error.minlength) ||
(personForm.mobile.$error.maxlength) ">Invalid mobile!</span>
<br /><br />
<label for="email">Email</label>
<input id="email" name="email" type="email" ng-model="person.email"
required />
<span class="error" ng-show="personForm.email.$error.required">Required!</span>
<span class="error" ng-show="personForm.email.$error.email">Invalid
Email!</span>
<br /><br />
<input type="checkbox" ng-model="terms" name="terms" id="terms"
required />
<label for="terms">I Agree to the terms.</label>
<span class="error" ng-show="personForm.terms.$error.required">You
must agree to the terms</span>

<br /><br />


<button type="submit">Submit Form</button>
<br /><br />
<span>{{msg}}</span>
</form>
</body>
</html>
PRACTICAL 7:
To create a real AngularJS Application for shopping Cart
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
<body>

<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
$scope.addItem = function () {
$scope.errortext = "";
if (!$scope.addMe) {return;}
if ($scope.products.indexOf($scope.addMe) == -1) {
$scope.products.push($scope.addMe);
} else {
$scope.errortext = "The item is already in your shopping list.";
}
}
$scope.removeItem = function (x) {
$scope.products.splice(x, 1);
}
});
</script>

<div ng-app="myShoppingList" ng-controller="myCtrl">


<ul>
<li ng-repeat="x in products">{{$index+1}} {{x}}<span ng-
click="removeItem($index)">×</span></li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">Add</button>
<p>{{errortext}}</p>
</div>

<p>Try to add the same item twice, and you will get an error message.</p>

</body>
</html>
PRACTICAL 8:
Write a Angular.js program to implement the concept of Single
page application
<!DOCTYPE html>
<!--ng-app directive tells AngularJS that myApp
is the root element of the application -->
<html ng-app="myApp">

<head>
<!--import the angularjs libraries-->
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular-route.min.js">
</script>

<style>
body {
text-align: center;
}

</style>
</head>

<body>
<h1>Practical 8</h1>
<h3>Single Page Application in AngularJS</h3>

<script type="text/ng-template" id="first.html">


<h1>First Page</h1>
<h2> Welcome to college </h2>
<h3>{{message}}</h3>
</script>
<script type="text/ng-template" id="second.html">
<h1>Second Page</h1> Start Learning WT
</h2>
<h3>{{message}}</h3>
</script>
<script type="text/ng-template" id="third.html">
<h1>Third Page</h1>
<h2> Contact us. </h2>
<h3>{{message}}</h3>
</script>

<a href="#/">First</a>
<a href="#/second">Second</a>
<a href="#/third">Third</a>
<div ng-view></div>

<script>
var app = angular.module('myApp', []);
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'first.html',
controller: 'FirstController'
})

.when('/second', {
templateUrl: 'second.html',
controller: 'SecondController'
})

.when('/third', {
templateUrl: 'third.html',
controller: 'ThirdController'
})

.otherwise({ redirectTo: '/' });


});

app.controller('FirstController', function ($scope) {


$scope.message = 'Hello from FirstController';
});
app.controller('SecondController', function ($scope) {
$scope.message = 'Hello from SecondController';
});
app.controller('ThirdController', function ($scope) {
$scope.message = 'Hello from ThirdController';
});
</script>
</body>

</html>
PRACTICAL 9:AngularJS Filters
9A uppercase

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | uppercase }}</p>
</div>
<script>
angular.module('myApp', []).controller('personCtrl', function($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe"
});
</script>
</body>
</html>

9b order-by
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<p>Looping with objects:</p>
<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
});
</script>
</body>
</html>
9c currency
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="costCtrl">
<h1>Price: {{ price | currency:"₹"}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('costCtrl', function($scope) {
$scope.price = 58;
});
</script>
<p>The currency filter formats a number to a currency format.</p>
</body>
</html>

9d filter
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.3/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<p>Type a letter in the input field:</p>
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in names | filter:test">
{{ x }}
</li>
</ul>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
'Jani',
'Carl',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
});
</script>
<p>The list will only consists of names matching the filter.</p>
</body>
</html>

You might also like