AWP HandBook ADVANCED WEB PROGRAMMING 3161611
AWP HandBook ADVANCED WEB PROGRAMMING 3161611
1.JavaScript Objects
With JavaScript, you can define and create your own objects.
for (x in person) {
txt += person[x];
}
JavaScript Object Methods
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
</script>
</body>
</html>
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that
allows programs and scripts to dynamically access and update the content, structure, and style
of a document."
The W3C DOM standard is separated into 3 different parts:
The HTML DOM is a standard object model and programming interface for HTML. It defines:
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.
<html>
<body>
<p id="demo"></p>
<script>
</script>
</body>
</html>
If you want to access any element in an HTML page, you always start with accessing the
document object.
Below are some examples of how you can use the document object to access and manipulate
HTML.
Method Description
Property Description
element. innerHTML = new html content Change the inner HTML of an element
Method Description
Method Description
Method Description
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and
properties. These are still valid in HTML5.
Later, in HTML DOM Level 3, more objects, collections, and properties were added.
Property Description DOM
To do so, you have to find the elements first. There are several ways to do this:
var x = document.getElementsByTagName("p");
var x = document.getElementsByClassName("intro");
var x = document.querySelectorAll("p.intro");
Ex:
<!DOCTYPE html>
<html>
<body>
</form>
<p>Click "Try it" to display the value of each element in the form.</p>
<script>
function myFunction() {
var x = document.forms["frm1"];
var i;
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
4. HTML events:
Ex.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("myBtn").onclick = displayDate;
function displayDate() {
document.getElementById("demo").innerHTML = Date();
</script>
</body>
</html>
Ex.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(x) {
x.style.background = "yellow";
</script>
</head>
<body>
<p>When the input field gets focus, a function is triggered which changes the
background-color.</p>
</body>
</html>
5. What is Bootstrap
Bootstrap 4 is the newest version of Bootstrap, which is the most popular HTML, CSS, and
JavaScript framework for developing responsive, mobile-first websites.
What is Bootstrap?
● Bootstrap is a free front-end framework for faster and easier web development
● Bootstrap includes HTML and CSS based design templates for typography, forms,
buttons, tables, navigation, modals, image carousels and many other, as well as optional
JavaScript plugins
● Bootstrap also gives you the ability to easily create responsive designs
Responsive web design is about creating web sites which automatically adjust themselves to
look good on all devices, from small phones to large desktops.
1. What Is AngularJS
AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
The ng-model directive binds the value of HTML controls (input, select, textarea) to application
data.
Ex.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
<p ng-bind="name"></p>
</div>
</body>
</html>
The ng-app directive tells AngularJS that the <div> element is the "owner" of an AngularJS
application.
The ng-model directive binds the value of the input field to the application variable name.
The ng-bind directive binds the content of the <p> element to the application variable name
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
<p>{{name}}</p>
</div>
</body>
</html>
2. AngularJS Applications
The ng-app directive defines the application, the ng-controller directive defines the controller.
Ex:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<br>
</div>
<script>
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>
</body>
</html>
3. AngularJS Expressions
AngularJS will resolve the expression, and return the result exactly where the expression is
written.
AngularJS expressions are much like JavaScript expressions: They can contain literals, operators,
and variables.
ex.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</div>
<p>The background color of the input box will be whatever you write in the input field.</p>
</body>
</html>
Ex.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="" ng-init="quantity=1;cost=5">
</div>
</body>
</html>
Ex.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</div>
</body>
</html>
Ex.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</div>
</body>
</html>
Ex.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</div>
</body>
</html>
4. AngularJS Modules
Creating a Module
A module is created by using the AngularJS function angular.module
<div ng-app="myApp">...</div>
<script>
</script>
The "myApp" parameter refers to an HTML element in which the application will run.
Now you can add controllers, directives, filters, and more, to your AngularJS application.
Adding a Controller
Add a controller to your application, and refer to the controller with the ng-controller directive:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
Adding a Directive
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "I was made in a directive constructor!"
};
});
</script>
</body>
</html>
It is common in AngularJS applications to put the module and the controllers in JavaScript files.
Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</div>
<script src="myApp.js"></script>
<script src="myCtrl.js"></script>
</body>
</html>
myApp.js
The [] parameter in the module definition can be used to define dependent modules.
Without the [] parameter, you are not creating a new module, but retrieving an existing one.
myCtrl.js
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName= "Doe";
});
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
<p>It is recommended that you load the AngularJS library either in the HEAD or at the start of
the BODY.</p>
</body>
</html>
6. AngularJS Directives
AngularJS lets you extend HTML with new attributes called Directives.
AngularJS has a set of built-in directives which offers functionality to your applications.
AngularJS Directives
AngularJS directives are extended HTML attributes with the prefix ng-.
The ng-model directive binds the value of HTML controls (input, select, textarea) to application
data.
Ex.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</div>
</body>
</html>
The ng-app directive also tells AngularJS that the <div> element is the "owner" of the AngularJS
application.
7. Data Binding
The {{ firstName }} expression, in the example above, is an AngularJS data binding expression.
In the next example two text fields are bound together with two ng-model directives:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<h2>Cost Calculator</h2>
</div>
</body>
</html>
Repeating HTML Elements
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</body>
</html>
The ng-repeat directive actually clones HTML elements once for each item in a collection.
Ex.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</div>
</body>
</html>
The ng-app directive will auto-bootstrap (automatically initialize) the application when a web
page is loaded.
Normally, you will not use ng-init. You will use a controller or module instead.
The ng-model directive binds the value of HTML controls (input, select, textarea) to application
data.
In addition to all the built-in AngularJS directives, you can create your own directives.
When naming a directive, you must use a camel case name, w3TestDirective, but when invoking
it, you must use - separated name, w3-test-directive:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<w3-test-directive></w3-test-directive>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "<h1>Made by a directive!</h1>"
};
});
</script>
</body>
</html>
● Element name
● Attribute
● Class
● Comment
Element name
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<w3-test-directive></w3-test-directive>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "<h1>Made by a directive!</h1>"
};
});
</script>
</body>
</html>
9. Attribute
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div w3-test-directive></div>
<script>
return {
};
});
</script>
</body>
</html>
Class
Ex.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div class="w3-test-directive"></div>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
restrict : "C",
};
});
</script>
<p><strong>Note:</strong> You must add the value "C" to the restrict property to be able to invoke
the directive from a class name.</p>
</body>
</html>
Restrictions
You can restrict your directives to only be invoked by some of the methods.
Example
By adding a restrict property with the value "A", the directive can only be invoked by attributes:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<w3-test-directive></w3-test-directive>
<div w3-test-directive></div>
<script>
app.directive("w3TestDirective", function() {
return {
restrict : "A",
};
});
</script>
</html>
By default the value is EA, meaning that both Element names and attribute names can invoke
the directive.
The ng-model directive binds the value of HTML controls (input, select, textarea) to application
data.
With the ng-model directive you can bind the value of an input field to a variable created in
AngularJS.
<!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="myCtrl">
</div>
<script>
app.controller('myCtrl', function($scope) {
});
</script>
<p>Use the ng-model directive to bind the value of the input field to a property made in the
controller.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</div>
<script>
app.controller('myCtrl', function($scope) {
});
</script>
<p>Change the name inside the input field, and you will see the name in the header changes
accordingly.</p>
</body>
</html>
The ng-model directive can provide type validation for application data (number, e-mail,
required):
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
Email:
</form>
<p>Enter your e-mail address in the input field. AngularJS will display an errormessage if the
address is not an e-mail.</p>
</body>
</html>
Application Status
The ng-model directive can provide status for application data (valid, dirty, touched, error):
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
Email:
<h1>Status</h1>
</form>
</body>
</html>
CSS Classes
The ng-model directive provides CSS classes for HTML elements, depending on their status:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<style>
input.ng-invalid {
background-color: lightblue;
</style>
<body>
</form>
<p>Edit the text field and it will get/lose classes according to the status.</p>
<p><b>Note:</b> A text field with the "required" attribute is not valid when it is empty.</p>
</body>
</html>
The ng-model directive adds/removes the following classes, according to the status of the form
field:
● ng-empty
● ng-not-empty
● ng-touched
● ng-untouched
● ng-valid
● ng-invalid
● ng-dirty
● ng-pending
● Ng-pristine
Data binding in AngularJS is the synchronization between the model and the view.
AngularJS Forms
Input Controls
● input elements
● select elements
● button elements
● textarea elements
Data-Binding
The ng-model directive binds the input controller to the rest of your application.
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname = "John";
});
</script>
</body>
</html>
Ex.
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.master = {firstName:"John", lastName:"Doe"};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
});
</script>
</body>
</html>
Form Validation
AngularJS offers client-side form validation.
AngularJS monitors the state of the form and input fields (input, textarea, select), and lets you
notify the user about the current state.
AngularJS also holds information about whether they have been touched, or modified, or not.
You can use standard HTML5 attributes to validate input, or you can make your own validation
functions.
Client-side validation cannot alone secure user input. Server side validation is also necessary.
Required
Use the HTML5 attribute required to specify that the input field must be filled out:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="">
<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>
</body>
</html>
Use the HTML5 type email to specify that the value must be an e-mail:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="">
<form name="myForm">
<input type="email" name="myInput" ng-model="myInput">
</form>
</body>
</html>
AngularJS is constantly updating the state of both the form and the input fields.
They are all properties of the input field, and are either true or false.
They are all properties of the form, and are either true or false.
You can use these states to show meaningful messages to the user. Example, if a field is
required, and the user leaves it blank, you should give the user a warning:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="">
<form name="myForm">
<p>Name:
<input name="myName" ng-model="myName" required>
<span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The name is
required.</span>
</p>
<p>Address:
<input name="myAddress" ng-model="myAddress" required>
</p>
</form>
<p>We use the ng-show directive to only show the error message if the field has been touched
AND is empty.</p>
</body>
</html>
CSS Classes
AngularJS adds CSS classes to forms and input fields depending on their states.
The following classes are added to, or removed from, input fields:
● ng-untouched The field has not been touched yet
● ng-touched The field has been touched
● ng-pristine The field has not been modified yet
● ng-dirty The field has been modified
● ng-valid The field content is valid
● ng-invalid The field content is not valid
● ng-valid-key One key for each validation. Example: ng-valid-required, useful when there
are more than one thing that must be validated
● ng-invalid-key Example: ng-invalid-required
Add styles for these classes to give your application a better and more intuitive user interface.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<style>
input.ng-invalid {
background-color:pink;
}
input.ng-valid {
background-color:lightgreen;
}
</style>
<body ng-app="">
<p>The input field requires content, and will therefore become green when you write in it.</p>
</body>
</html>
To create your own validation function is a bit more tricky; You have to add a new directive to
your application, and deal with the validation inside a function with certain specified
arguments.
Example
Create your own directive, containing a custom validation function, and refer to it by using
my-directive.
The field will only be valid if the value contains the character "e":
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<form name="myForm">
<input name="myInput" ng-model="myInput" required my-directive>
</form>
<script>
var app = angular.module('myApp', []);
app.directive('myDirective', function() {
return {
require: 'ngModel',
link: function(scope, element, attr, mCtrl) {
function myValidation(value) {
if (value.indexOf("e") > -1) {
mCtrl.$setValidity('charE', true);
} else {
mCtrl.$setValidity('charE', false);
}
return value;
}
mCtrl.$parsers.push(myValidation);
}
};
});
</script>
<p>The input field must contain the character "e" to be consider valid.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<h2>Validation Example</h2>
<p>Username:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">Username is required.</span>
</span>
</p>
<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>
<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.user = 'John Doe';
$scope.email = '[email protected]';
});
</script>
</body>
</html>
The ngRoute module helps your application to become a Single Page Application.
If you want to navigate to different pages in your application, but you also want the application
to be a SPA (Single Page Application), with no page reloading, you can use the ngRoute module.
The ngRoute module routes your application to different pages without reloading the entire
application.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
<body ng-app="myApp">
<p><a href="#/!">Main</a></p>
<a href="#!red">Red</a>
<a href="#!green">Green</a>
<a href="#!blue">Blue</a>
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/red", {
templateUrl : "red.htm"
})
.when("/green", {
templateUrl : "green.htm"
})
.when("/blue", {
templateUrl : "blue.htm"
});
});
</script>
<p>Click on the links to navigate to "red.htm", "green.htm", "blue.htm", or back to
"main.htm"</p>
</body>
</html>
What do I Need?
To make your applications ready for routing, you must include the AngularJS Route module:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
Then you must add the ngRoute as a dependency in the application module:
Now your application has access to the route module, which provides the $routeProvider.
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/red", {
templateUrl : "red.htm"
})
.when("/green", {
templateUrl : "green.htm"
})
.when("/blue", {
templateUrl : "blue.htm"
});
});
Your application needs a container to put the content provided by the routing.
There are three different ways to include the ng-view directive in your application:
Ex.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<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.errortext = "";
$scope.products.splice(x, 1);
}
});
</script>
</body>
</html>
1. What is Node.js?
Why Node.js?
A common task for a web server can be to open a file on the server and return the content to
the client.
Node.js eliminates the waiting, and simply continues with the next request.
Node.js runs single-threaded, non-blocking, asynchronously programming, which is very
memory efficient.
myfirst.js
C:\Users>node myfirst.js
Include Modules
To include a module, use the require() function with the name of the module:
Now your application has access to the HTTP module, and is able to create a server:
res.end('Hello World!');
}).listen(8080);
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
exports.myDateTime = function () {
return Date();
};
Use the exports keyword to make properties and methods available outside the module file.
Now you can include and use the module in any of your Node.js files.
Example
var dt = require('./myfirstmodule');
res.end();
}).listen(8080);
Notice that we use ./ to locate the module, that means that the module is located in the same
folder as the Node.js file.
Save the code above in a file called "demo_module.js", and initiate the file:
Initiate demo_module.js:
Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper
Text Transfer Protocol (HTTP).
The HTTP module can create an HTTP server that listens to server ports and gives a response
back to the client.
Use the createServer() method to create an HTTP server:
EX.
If the response from the HTTP server is supposed to be displayed as HTML, you should include
an HTTP header with the correct content type:
Example
res.write('Hello World!');
res.end();
}).listen(8080);
The function passed into the http.createServer() has a req argument that represents the
request from the client, as an object (http.IncomingMessage object).
This object has a property called "url" which holds the part of the url that comes after the
domain name:
demo_http_url.js
res.end();
}).listen(8080);
There are built-in modules to easily split the query string into readable parts, such as the URL
module.
Example
res.end(txt);
}).listen(8080);
var fs = require('fs');
● Read files
● Create files
● Update files
● Delete files
● Rename files
Read Files
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 fs = require('fs');
res.write(data);
return res.end();
});
}).listen(8080);
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:
Example
console.log('Saved!');
});
4. Node.js NPM
What is NPM?
The NPM program is installed on your computer when you install Node.js
What is a Package?
A package in Node.js contains all the files you need for a module.
Download a Package
Open the command line interface and tell NPM to download the package you want.
Download "upper-case":
C:\Users\Your Name>npm install upper-case
NPM creates a folder named "node_modules", where the package will be placed. All packages
you install in the future will be placed in this folder.
C:\Users\My Name\node_modules\upper-case
Using a Package
Include the "upper-case" package the same way you include any other module:
var uc = require('upper-case');
Create a Node.js file that will convert the output "Hello World!" into upper-case letters:
Example
var uc = require('upper-case');
res.write(uc.upperCase("Hello World!"));
res.end();
}).listen(8080);
5. Node.js Events
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 () {
});
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:
You can assign event handlers to your own events with the EventEmitter object.
In the example below we have created a function that will be executed when a "scream" event
is fired.
Ex
var events = require('events');
var eventEmitter = new events.EventEmitter();
Node.js MongoDB
reating a Database
MongoDB will create the database if it does not exist, and make a connection to it.
Example
console.log("Database created!");
db.close();
});
Save the code above in a file called "demo_create_mongo_db.js" and run the file:
Run "demo_create_mongo_db.js"
MongoDB waits until you have created a collection (table), with at least one document (record)
before it actually creates the database (and collection).
Example
console.log("Collection created!");
db.close();
});
});
Save the code above in a file called "demo_mongodb_createcollection.js" and run the file:
Run "demo_mongodb_createcollection.js"
C:\Users\Your Name>node demo_mongodb_createcollection.js
Collection created!
The first parameter of the insertOne() method is an object containing the name(s) and value(s)
of each field in the document you want to insert.
It also takes a callback function where you can work with any errors, or the result of the
insertion:
Example
db.close();
});
});
Note: If you try to insert documents in a collection that do not exist, MongoDB will create the
collection automatically.
To insert multiple documents into a collection in MongoDB, we use the insertMany() method.
The first parameter of the insertMany() method is an array of objects, containing the data you
want to insert.
It also takes a callback function where you can work with any errors, or the result of the
insertion:
Example
var myobj = [
db.close();
});
});
The result object contains information about how the insertion affected the database.
If you do not specify an _id field, then MongoDB will add one for you and assign a unique id for
each document.
In the example above no _id field was specified, and as you can see from the result object,
MongoDB assigned a unique _id for each document.
If you do specify the _id field, the value must be unique for each document:
Example
var myobj = [
];
console.log(res);
db.close();
});
});
In MongoDB we use the find and findOne methods to find data in a collection.
Just like the SELECT statement is used to find data in a table in a MySQL database.
Find One
To select data from a collection in MongoDB, we can use the findOne() method.
The first parameter of the findOne() method is a query object. In this example we use an empty
query object, which selects all documents in a collection (but returns only the first document).
Example
console.log(result.name);
db.close();
});
});
Find All
To select data from a table in MongoDB, we can also use the find() method.
The first parameter of the find() method is a query object. In this example we use an empty
query object, which selects all documents in the collection.
No parameters in the find() method gives you the same result as SELECT * in MySQL.
Example
dbo.collection("customers").find({}).toArray(function(err, result) {
console.log(result);
db.close();
});
});
Find Some
The second parameter of the find() method is the projection object that describes which fields
to include in the result.
This parameter is optional, and if omitted, all fields will be included in the result.
Example
Return the fields "name" and "address" of all documents in the customers collection:
console.log(result);
db.close();
});
});
To return e.g. the address of the third document, just refer to the third array object's address
property:
Example
console.log(result[2].address);
Apple st 652
When finding documents in a collection, you can filter the result by using a query object.
The first argument of the find() method is a query object, and is used to limit the search.
Example
dbo.collection("customers").find(query).toArray(function(err, result) {
console.log(result);
db.close();
});
});
You can write regular expressions to find exactly what you are searching for.
To find only the documents where the "address" field starts with the letter "S", use the regular
expression /^S/:
Example
Find documents where the address starts with the letter "S":
dbo.collection("customers").find(query).toArray(function(err, result) {
console.log(result);
db.close();
});
});
Use the sort() method to sort the result in ascending or descending order.
The sort() method takes one parameter, an object defining the sorting order.
Example
dbo.collection("customers").find().sort(mysort).toArray(function(err, result) {
console.log(result);
db.close();
});
});
Sort Descending
{ name: 1 } // ascending
{ name: -1 } // descending
Example
Sort the result reverse alphabetically by name:
dbo.collection("customers").find().sort(mysort).toArray(function(err, result) {
console.log(result);
db.close();
});
});
Delete Document
The first parameter of the deleteOne() method is a query object defining which document to
delete.
Note: If the query finds more than one document, only the first occurrence is deleted.
Example
db.close();
});
});
Delete Many
Example
Delete all documents were the address starts with the letter "O":
db.close();
});
});
Node.js MongoDB Update
Update Document
You can update a record, or document as it is called in MongoDB, by using the updateOne()
method.
The first parameter of the updateOne() method is a query object defining which document to
update.
Note: If the query finds more than one record, only the first occurrence is updated.
The second parameter is an object defining the new values of the document.
Example
Update the document with the address "Valley 345" to name="Mickey" and address="Canyon 123":
db.close();
});
});
When using the $set operator, only the specified fields are updated:
Ex.
});
});
To update all documents that meets the criteria of the query, use the updateMany() method.
db.close();
});
});