0% found this document useful (0 votes)
144 views29 pages

Unit 2 WT

The document discusses AngularJS and Node.js fundamentals. It provides an introduction to AngularJS including how it uses HTML and JavaScript to create dynamic web applications. It also discusses AngularJS expressions, arrays, objects and strings. The document then covers Node.js fundamentals like advantages, process model and modules. Finally, it summarizes AngularJS form validation and submission.

Uploaded by

Anitha Damarla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
144 views29 pages

Unit 2 WT

The document discusses AngularJS and Node.js fundamentals. It provides an introduction to AngularJS including how it uses HTML and JavaScript to create dynamic web applications. It also discusses AngularJS expressions, arrays, objects and strings. The document then covers Node.js fundamentals like advantages, process model and modules. Finally, it summarizes AngularJS form validation and submission.

Uploaded by

Anitha Damarla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

UNIT -2

Fundamentals of Angular JS and NODE JS Angular Java Script- Introduction to Angular JS Expressions:
ARRAY, Objects, Strings, Angular JS Form Validation & Form Submission. Node.js- Introduction,
Advantages, Node.js Process Model, Node JS Modules, Node JS File system, Node JS URL module, Node
JS Events.

Introduction to Angular JS
 AngularJS is an open source JavaScript MVC framework for web application or web sites.
It extends the HTML and makes it dynamic. AngularJS can be used to create Single Page
Applications.
 AngularJS was originally started as a project in Google but now, it is open source
framework.
 AngularJS is entirely based on HTML and JavaScript, so there is no need to learn another
syntax or language.
 AngularJS changes static HTML to dynamic HTML.
 It extends the ability of HTML by adding built-in attributes and components and also
provides an ability to create custom attributes using simple JavaScript.

Advantages of AngularJS
 Open source JavaScript MVC framework.
 Supported by Google
 No need to learn another scripting language. It's just pure JavaScript and HTML.
 Supports separation of concerns by using MVC design pattern.
 Built-in attributes (directives) makes HTML dynamic.
 Easy to extend and customize.
 Supports Single Page Application.
 Uses Dependency Injection.
 Easy to Unit test.
 REST friendly.

AngularJS Expression
AngularJS expression is like JavaScript expression surrounded with braces - {{ expression }}. AngularJS
evaluates the specified expression and binds the result data to HTML.

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


AngularJS expression can contain literals, operators and variables like JavaScript expression. For
example, an expression {{2/2}} will produce the result 1 and will be bound to HTML.

Example: Expression

<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body >
<h1>AngularJS Expression Demo:</h1>
<div ng-app>
2 + 2 = {{2 + 2}} <br />
2 - 2 = {{2 - 2}} <br />
2 * 2 = {{2 * 2}} <br />
2 / 2 = {{2 / 2}}
</div>
</body>
</html>

Result:
2 + 2 = 4
2 - 2 = 0
2 * 2 = 4
2 / 2 = 1
AngularJS expression is like JavaScript code expression except for the following differences:

 AngularJS expression cannot contain conditions, loops, exceptions or regular


expressions e.g. if-else, ternary, for loop, while loop etc.
 AngularJS expression cannot declare functions.
 AngularJS expression cannot contain comma or void.
 AngularJS expression cannot contain return keyword.

Example: Expression
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body >

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


<h1>AngularJS Expression Demo:</h1>
<div ng-app>
{{"Hello World"}}<br />
{{100}}<br />
{{true}}<br />
{{10.2}}
</div>
</body>
</html>
Try it
Result:
Hello World
100
True
10.2

AngularJS Arrays
Expressions can be used to work with arrays as well. Let’s look at an example of Angular JS expressions
with arrays.

In this example, we are going to define an array which is going to hold the marks of a student in 3
subjects. In the view, we will display the value of these marks accordingly.

<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>

<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>

<h1> VITW</h1>

<div ng-app="" ng-init="marks=[1,15,19]">

Student Marks<br>&nbsp;&nbsp;&nbsp;
Subject1 : {{marks[0] }}<br>&nbsp;&nbsp;&nbsp;
Subject2 : {{marks[1] }}<br>&nbsp;&nbsp;&nbsp;
Subject3 : {{marks[2] }}<br>&nbsp;&nbsp;&nbsp;
</div>

</body>
</html>

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


Code Explanation:

 The ng-init directive is used define the array with the name “marks” with 3 values of 1, 15 and
19.
 We are then using expressions of marks [index] to access each element of the array.
 If the code is executed successfully, the following Output will be shown when you run your code
in the browser.

OUTPUT:

Student Marks

Subject1 : 1
Subject2 : 15
Subject3 :19

Angular.JS Objects
 Expressions can be used to work with JavaScript objects as well.
 Let’s look at an example of Angular.JS expressions with javascript objects. A javascript object
consists of a name-value pair.

Below is an example of the syntax of a javascript object.

Syntax:

var car = {type:"Ford", model:"Explorer", color:"White"};

In this example, we are going to define one object as a person object which will have 2 key value pairs of
“firstName” and “lastName”.

EXAMPLE CODE:

<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>

</head>
<body>

<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>

<h1> WELCOME TO EVENT</h1>

<div ng-app="" ng-init="person={firstName:'SHALINI',lastName:'TAMMANA'}">

&nbsp;&nbsp;&nbsp;
First Name : {{person.firstName}}<br>&nbsp;&nbsp;&nbsp;
Last Name : {{person.lastName}}

</div>

</body>
</html>
Code Explanation:

 The ng-init directive is used to define the object person which in turn has key value pairs of
firstName with the value “SHALINI” and the variable lastName with the value of “TAMMANA”.
 We are then using expressions of {{person.firstName}} and {{person.secondName}} to access the
value of these variables and display them in the view accordingly. Since the actual member
variables are part of the object person, they have to access it with the dot (.) notation to access
their actual value.

If the code is executed successfully, the following Output will be shown when you run your code in the
browser.

OUTPUT:

WELCOME TO EVENT

firstName: SHALINI

lastName: TAMMANA

AngularJS Strings
 Expressions can be used to work with strings as well. Let’s look at an example of Angular JS
expressions with strings.
 In this example, we are going to define 2 strings of “firstName” and “lastName” and display
them using expressions accordingly.

<!DOCTYPE html>
<html>
<head>

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


<meta chrset="UTF 8">
<title>Event Registration</title>

</head>
<body>

<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>

<h1> Global Event</h1>

<div ng-app="" ng-init="firstName='shalini';lastName='tammana'">

&nbsp;&nbsp;&nbsp;
First Name : {{firstName}}<br>&nbsp;&nbsp;&nbsp;
last Name : {{lastName}}

</div>

</body>
</html>

Code Explanation:

 The ng-init directive is used define the variables firstName with the value “Guru” and the
variable lastName with the value of “99”.
 We are then using expressions of {{firstName}} and {{lastName}} to access the value of these
variables and display them in the view accordingly.

If the code is executed successfully, the following Output will be shown when you run your code in the
browser.

Output:

GLOBAL EVENT

firstName: SHALINI

lastName: TAMMANA

AngularJS Form Validation & FORM Submission


 Form Validation in AngularJS is the process of ensuring whether the data entered in a form is
correct and complete.
 When a user submits the form, validation occurs first before the details are sent to the server.
The validation process ensures at best possible extent that the details for input fields are
entered in the right manner.

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


 In a real-world example, let’s assume a site which requires a registration form to be completed
before getting full access to this site. The registration page would have input fields for
username, password, email id and so forth.
 For example, the email id always needs to be in a format of [email protected]; if someone
enters just the username in the email id, then ideally the validation should fail. So validation
looks at doing these basic checks before the details are sent to the server for further processing.

*****Angular JS Form Validation & Form Submission.*********

Validation in AngularJS
We created an HTML form in the previous section. Here, we will implement client side validation in
AngularJS form.

AngularJS includes the following validation directives.

Directive Description

ng-required Sets required attribute on an input field.

ng-minlength Sets minlength attribute on an input field.

ng- Sets maxlength attribute on an input field. Setting the attribute to a negative or non-numeric value, allows v
maxlength length.

ng-pattern Sets pattern validation error key if the ngModel value does not match the specified RegEx expression.

Let's implement validation in the student form which contains First Name, Last Name and Email fields.

<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app >
<form name="studentForm" novalidate>
<label for="firstName">First Name: </label> <br />
<input type="text" name="firstName" ng-
model="student.firstName" ng-required="true" />
<span ng-show="studentForm.firstName.$touched &&
studentForm.firstName.$error.required">First name is
required.</span><br /><br />
<label for="lastName">Last Name</label><br />

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


<input type="text" name="lastName" ng-minlength="3" ng-
maxlength="10" ng-model="student.lastName" />
<span ng-show="studentForm.lastName.$touched &&
studentForm.lastName.$error.minlength">min 3 chars.</span>
<span ng-show="studentForm.lastName.$touched &&
studentForm.lastName.$error.maxlength">Max 10 chars.</span><br /><br
/>
<label for="dob">Email</label><br />
<input type="email" id="email" ng-model="student.email"
name="email" />
<span ng-show="studentForm.email.$touched &&
studentForm.email.$error.email">Please enter valid email id.</span><br
/><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

EXPLANATION step by step:

 Apply novalidate attribute in <form> tag. The novalidate attribute will disable the browser's
default validation.
 Set the name attribute in <form> and other elements, which will be used to obtain a reference
of the elements.

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


 Now, set ng-required="true" on the input element of First Name. Also, set name attribute to the
name of model property, "firstName" in this case.
 Create <span> element to specify an error message with every input filed where the validation
directive is applied.
 Set ng-show directives to <span> element to an expression "studentForm.firstName.$touched
&& studentForm.firstName.$error.required". This expression will return true if a user tabbed
out without entering FirstName.
 The same way set ng-minlength & ng-maxlength directives to last name. Also, set ng-show
directive to "studentForm.lastName.$touched && studentForm.lastName.$error.minlength"
expression to <span> element adjacent to LastName input field.
 Create another <span> for maxlength validation message.
 Email will be validated automatically with input type=email. Also, create <span> for email
validation message.
 We have applied an expression "studentForm.firstName.$touched && studentForm.firstName.
$error.required" to the <span>, in the above example. $touched & $error are built-in properties
which return the state of the specified input controls and form. Let's learn about the state
properties.

AngularJS Forms

 The HTML form is a collection of input controls where user can enter the data. Here, you will
learn how to display AngularJS form and submit the data.
 An AngularJS Form Example
 We will create following Student Information form with submit and reset functionality.

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


Sample AngularJS Form

The following is the code of the above form.

Example: AngularJS Form

<!DOCTYPE html>
<html ng-app="studentApp">
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-controller="studentController">
<h1>Student Information:</h1>
<form ng-submit="submitStudnetForm()" >
<label for="firstName" >First Name: </label><br />
<input type="text" id="firstName" ng-
model="student.firstName" /> <br />

<label for="lastName">Last Name</label><br />


<input type="text" id="lastName" ng-
model="student.lastName" /> <br />
<label for="dob" >DoB</label><br />
<input type="date" id="dob" ng-model="student.DoB" />
<br /><br />

<label for="gender" >Gender</label> <br />

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


<select id="gender" ng-model="student.gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select><br /> <br />
<span>Training Type:</span><br />
<label><input value="online" type="radio"
name="training" ng-model="student.trainingType" />Online</label><br />
<label><input value="onsite" type="radio"
name="training" ng-model="student.trainingType" />OnSite</label> <br
/><br />
<span>Subjects</span><br />
<label><input type="checkbox" ng-
model="student.maths" />Maths</label> <br />
<label><input type="checkbox" ng-
model="student.physics" />Physics</label> <br />
<label><input type="checkbox" ng-
model="student.chemistry" />Chemistry</label><br /><br />

<input type="submit" value="Submit" />


<input type="reset" ng-click="resetForm()" value="Reset" />
</form>
<script>
//1. create app module
var studentApp = angular.module('studentApp', []);

//2. create controller


studentApp.controller("studentController", function ($scope,
$http) {

//3. attach originalStudent model object


$scope.originalStudent = {
firstName: 'James',
lastName: 'Bond',
DoB: new Date('01/31/1980'),
gender: 'male',
trainingType: 'online',
maths: false,
physics: true,
chemistry: true
};

//4. copy originalStudent to student. student will be bind


to a form
$scope.student = angular.copy($scope.originalStudent);

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


//5. create submitStudentForm() function. This will be
called when user submits the form
$scope.submitStudnetForm = function () {

var onSuccess = function (data, status, headers,


config) {
alert('Student saved successfully.');
};

var onError = function (data, status, headers, config)


{
alert('Error occured.');
}

$http.post('/student/submitData', { student:
$scope.student })
.success(onSuccess)
.error(onError);

};

//6. create resetForm() function. This will be called on


Reset button click.
$scope.resetForm = function () {
$scope.student = angular.copy($scope.OriginalStudent);
};
});
</script>
</body>
</html>

Output:

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


The following is a step by step explanation of the above example:

 Create an HTML page and wrap all the necessary input controlls into <form> tag.
 Create the AngularJS application module in the <script> tag.
 Create studentController in application module.
 Create originalStudent object and attach to the $scope with required properties. This will stay
unchanged during entire life cycle.
 Create new student object and attach to the $scope and copy all the properties and values from
originalStudent. This student object will be bound to the form using ng-model directive.
Therefore, if user changes form values then the student object will also get changed.
 Create submitStudnetForm function which will get called when user submits the form using
Submit button. Here, send http POST request to the remote server to submit the data
using $http service.
 Create resetForm() function, which will reset the form values to the originalStudent values by
copying it to student object.
 Apply ng-app, ng-controller directives.
 Apply ng-model directives to each HTML input element to bind appropriate properties of
student object.
 Apply ng-submit directive to form which will call submitStudentForm() on the form submit
event.
 Apply ng-click directive to reset button which will call resetForm() on the button click event.
 An AngularJS form can be submitted using either ng-submit or ng-click directive but not both.

Ng-submit: Binds angular expression to onsubmit event when form does not include action attribute.

Ng-click: Binds angular expression to onclick event.

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


NODE JS

Introduction:
 Node.js is an open source, cross-platform runtime environment for developing server-side and
networking applications. Node.js applications are written in JavaScript, and can be run within
the Node.js runtime on OS X, Microsoft Windows, and Linux.
 Node.js also provides a rich library of various JavaScript modules which simplifies the
development of web applications using Node.js to a great extent.

Node.js = Runtime Environment + JavaScript Library

Features of Node.js

Following are some of the important features that make Node.js the first choice of software architects.

 Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-
blocking. It essentially means a Node.js based server never waits for an API to return data. The
server moves to the next API after calling it and a notification mechanism of Events of Node.js
helps the server to get a response from the previous API call.
 Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in
code execution.
 Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping.
Event mechanism helps the server to respond in a non-blocking way and makes the server highly
scalable as opposed to traditional servers which create limited threads to handle requests.
Node.js uses a single threaded program and the same program can provide service to a much
larger number of requests than traditional servers like Apache HTTP Server.
 No Buffering − Node.js applications never buffer any data. These applications simply output the
data in chunks.

Where to Use Node.js?

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


Following are the areas where Node.js is proving itself as a perfect technology partner.

 I/O bound Applications


 Data Streaming Applications
 Data Intensive Real-time Applications (DIRT)
 JSON APIs based Applications
 Single Page Applications

ADVANTAGES:
 Efficient performance.
 Easier development process.
 Reusable code.
 Ability to handle multiple requests.
 Ability to scale smoothly.
 Prompt code execution.
 Asynchronous and event-driven.
 Supported by leading companies.

Node.js Process Model


In this section, we will learn about the Node.js process model and
understand why we should use Node.js.

Traditional Web Server Model


In the traditional web server model, each request is handled by a
dedicated thread from the thread pool. If no thread is available in the
thread pool at any point of time then the request waits till the next
available thread. Dedicated thread executes a particular request and
does not return to thread pool until it completes the execution and
returns a response.

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


Traditional Web Server Model

Node.js Process Model


Node.js processes user requests differently when compared to a traditional web server model. Node.js
runs in a single process and the application code runs in a single thread and thereby needs less
resources than other platforms. All the user requests to your web application will be handled by a single
thread and all the I/O work or long running job is performed asynchronously for a particular request. So,
this single thread doesn't have to wait for the request to complete and is free to handle the next
request. When asynchronous I/O work completes then it processes the request further and sends the
response.

An event loop is constantly watching for the events to be raised for an asynchronous job and executing
callback function when the job completes. Internally, Node.js uses libev for the event loop which in turn
uses internal C++ thread pool to provide asynchronous I/O.

The following figure illustrates asynchronous web server model using Node.js.

Node.js Process Model

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


Node.js process model increases the performance and scalability with a few caveats. Node.js is not fit
for an application which performs CPU-intensive operations like image processing or other heavy
computation work because it takes time to process a request and thereby blocks the single thread.

What is a Module in Node.js?


Consider modules to be the same as JavaScript libraries.

A set of functions you want to include in your application.

Built-in Modules

Node.js has a set of built-in modules which you can use without any further installation.

Look at our Built-in Modules Reference for a complete list of modules.

Include Modules

To include a module, use the require() function with the name of the module:

var http = require('http');

Now your application has access to the HTTP module, and is able to create a server:

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('Hello World!');
}).listen(8080);

Create Your Own Modules

You can create your own modules, and easily include them in your applications.

The following example creates a module that returns a date and time object:

Example

Create a module that returns the current date and time:

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


exports.myDateTime = function () {
  return Date();
};

Use the exports keyword to make properties and methods available outside the module file.

Save the code above in a file called "myfirstmodule.js"

Include Your Own Module

Now you can include and use the module in any of your Node.js files.

Example
Use the module "myfirstmodule" in a Node.js file:

var http = require('http');
var dt = require('./myfirstmodule');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("The date and time are currently: " + dt.myDateTime());
  res.end();
}).listen(8080);

Node JS File system

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


Node.js as a File Server
The Node.js file system module allows you to work with the file system on your
computer.

To include the File System module, use the require() method:

var fs = require('fs');

Common use for the File System module:

 Read files
 Create files
 Update files
 Delete files
 Rename files

Read Files
The fs.readFile() method is used to read files on your computer.

Assume we have the following HTML file (located in the same folder as Node.js):

demofile1.html

<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>

Create a Node.js file that reads the HTML file, and return the content:

Example
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


  fs.readFile('demofile1.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

Save the code above in a file called "demo_readfile.js", and initiate the file:

Initiate demo_readfile.js:

C:\Users\Your Name>node demo_readfile.js

Create Files
The File System module has methods for creating new files:

 fs.appendFile()
 fs.open()
 fs.writeFile()

The fs.appendFile() method appends specified content to a file. If the file does


not exist, the file will be created:

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


Example
Create a new file using the appendFile() method:

var fs = require('fs');

fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
  if (err) throw err;
  console.log('Saved!');
});

The fs.open() method takes a "flag" as the second argument, if the flag is "w"


for "writing", the specified file is opened for writing. If the file does not exist, an
empty file is created:

Example
Create a new, empty file using the open() method:

var fs = require('fs');

fs.open('mynewfile2.txt', 'w', function (err, file) {
  if (err) throw err;
  console.log('Saved!');
});

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


The fs.writeFile() method replaces the specified file and content if it exists. If
the file does not exist, a new file, containing the specified content, will be
created:

Example
Create a new file using the writeFile() method:

var fs = require('fs');

fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {
  if (err) throw err;
  console.log('Saved!');

});

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


Update Files
The File System module has methods for updating files:

 fs.appendFile()
 fs.writeFile()

The fs.appendFile() method appends the specified content at the end of the


specified file:

Example
Append "This is my text." to the end of the file "mynewfile1.txt":

var fs = require('fs');

fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) {


  if (err) throw err;
  console.log('Updated!');
});

C:\Users\My Name>node demo_fs_update.js


Updated!

The fs.writeFile() method replaces the specified file and content:

Example
Replace the content of the file "mynewfile3.txt":

var fs = require('fs');

fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {
  if (err) throw err;
  console.log('Replaced!');
});

C:\Users\My Name>node demo_fs_replace.js


Replaced!

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


Delete Files
To delete a file with the File System module,  use the fs.unlink() method.

The fs.unlink() method deletes the specified file:

Example
Delete "mynewfile2.txt":

var fs = require('fs');

fs.unlink('mynewfile2.txt', function (err) {
  if (err) throw err;
  console.log('File deleted!');
});

C:\Users\My Name>node demo_fs_unlink.js


File deleted!

Rename Files
To rename a file with the File System module,  use the fs.rename() method.

The fs.rename() method renames the specified file:

Example
Rename "mynewfile1.txt" to "myrenamedfile.txt":

var fs = require('fs');

fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
  if (err) throw err;
  console.log('File Renamed!');
});

C:\Users\My Name>node demo_fs_rename.js


File Renamed!

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


Upload Files
You can also use Node.js to upload files to your computer.

Node.js URL Module

The Built-in URL Module


The URL module splits up a web address into readable parts.

To include the URL module, use the require() method:

var url = require('url');

Parse an address with the url.parse() method, and it will return a URL object


with each part of the address as properties:

Example
Split a web address into readable parts:

var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);

console.log(q.host); //returns 'localhost:8080'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'

var qdata = q.query; //returns an object: { year: 2017, month: 'february'


}
console.log(qdata.month); //returns 'february'

C:\Users\My Name>node demo_url.js


localhost:8080
/default
?year=2017&month=february
february

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


Node.js File Server
Now we know how to parse the query string, and in the previous chapter we
learned how to make Node.js behave as a file server. Let us combine the two,
and serve the file requested by the client.

Create two html files and save them in the same folder as your node.js files.

summer.html

<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>

winter.html

<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love the snow!</p>
</body>
</html>

Create a Node.js file that opens the requested file and returns the content to
the client. If anything goes wrong, throw a 404 error:

demo_fileserver.js:

var http = require('http');
var url = require('url');
var fs = require('fs');

http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;
  fs.readFile(filename, function(err, data) {
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'});
      return res.end("404 Not Found");

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


    } 
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

Remember to initiate the file:

Initiate demo_fileserver.js:

C:\Users\Your Name>node demo_fileserver.js

If you have followed the same steps on your computer, you should see two
different results when opening these two addresses:

http://localhost:8080/summer.html

Will produce this result:

Summer
I love the sun!

http://localhost:8080/winter.html

Will produce this result:

Winter
I love the snow!

Node.js Events
Node.js is perfect for event-driven applications.

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


Events in Node.js
Every action on a computer is an event. Like when a connection is made or a
file is opened.

Objects in Node.js can fire events, like the readStream object fires events when
opening and closing a file:

Example
var fs = require('fs');
var rs = fs.createReadStream('./demofile.txt');
rs.on('open', function () {
  console.log('The file is open');
});

C:\Users\My Name>node demo_events_open.js


The file is open

Events Module
Node.js has a built-in module, called "Events", where you can create-, fire-, and
listen for- your own events.

To include the built-in Events module use the require() method. In addition, all


event properties and methods are an instance of an EventEmitter object. To be
able to access these properties and methods, create an EventEmitter object:

var events = require('events');
var eventEmitter = new events.EventEmitter();

The Event Emitter Object


You can assign event handlers to your own events with the EventEmitter object.

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN


In the example below we have created a function that will be executed when a
"scream" event is fired.

To fire an event, use the emit() method.

Example
var events = require('events');
var eventEmitter = new events.EventEmitter();

//Create an event handler:


var myEventHandler = function () {
  console.log('I hear a scream!');
}

//Assign the event handler to an event:


eventEmitter.on('scream', myEventHandler);

//Fire the 'scream' event:


eventEmitter.emit('scream');

C:\Users\My Name>node demo_eventemitter.js


I hear a scream!

VIJAYA INSTITUTE OF TECHNOLOGY FOR WOMEN

You might also like