KEMBAR78
MST Lab Manual | PDF | Java Script | Relational Database
0% found this document useful (0 votes)
50 views42 pages

MST Lab Manual

Node.js is an open-source JavaScript runtime environment that allows JavaScript to run on the server-side. The V8 engine, developed by Google, is a JavaScript engine that executes JavaScript code and powers Node.js. V8 first compiles JavaScript code into machine code using just-in-time compilation before executing it. Node.js relies on the V8 engine to run JavaScript code on the server and provides APIs to build scalable network and database applications.

Uploaded by

Hanish Manikanta
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)
50 views42 pages

MST Lab Manual

Node.js is an open-source JavaScript runtime environment that allows JavaScript to run on the server-side. The V8 engine, developed by Google, is a JavaScript engine that executes JavaScript code and powers Node.js. V8 first compiles JavaScript code into machine code using just-in-time compilation before executing it. Node.js relies on the V8 engine to run JavaScript code on the server and provides APIs to build scalable network and database applications.

Uploaded by

Hanish Manikanta
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/ 42

EXPERIMENT-1

Introduction to Node JS

The mean stack is a JavaScript-based framework for developing web applications. MEAN is named after
MongoDB, Express, Node and Angular, the four key technologies that make up the layers of thestack.

Node.js

Node.js is an open-source platform and provides a runtime environment for executing the javascript code. It is
mainly used for building the back-end application. Since there are two types of apps, such as web apps and
mobile apps, where web apps run on the browser and mobile apps run on mobile devices. Both web app and
mobile app are the client apps to whichthe user interacts. These apps require to communicate with the backend
services to store the data, send emails, push notifications. Node.js is an ideal platform to build highly scalable,
data-intensive, and real-time applications. It can be used for agile development and highly-scalableservices.
For example, PayPal is a java and spring-based application using Node.js.

Angular.js

Angular.js is a JavaScript framework that is used to develop web applications. This frameworkis developed by
the Google. Now, the question arises that there are many javascript frameworks available in the market.

MongoDB

MongoDB is the database used in web development. It is a NoSQL database, and a NoSQL database can be
defined as a non-relational and document-oriented database management system. As it is a document-oriented
database management system, so it stores the data in the form of documents. The SQL databases use SQL
query language to query the database, whereas the MongoDB is a NoSQL database that uses BSON language
to query the database.

Express.js

Express.js is a free and open-source software used as a back-end web application framework.It is commonly
used in the popular development stacks like MEAN with a MongoDB database.The Express.js was developed
by TJ Holowaychuk.
EXPERIMENT-2
Exploring language addition to V8 JavaScript Engine

What is a V8 Engine?
V8 is a C++-based open-source JavaScript engine developed by Google. It was originally designed
for Google Chrome and Chromium-based browsers (such as Brave) in 2008, but it was later utilized
to create Node.js for server-side coding. Inreality, JSON-based No-SQL databases like Couchbase
and the widely used MongoDB use the V8 engine. V8 also powers Electron, a prominent desktop
application framework, and Demo, the latest server-side runtime environment.
V8 is known to be a JavaScript engine because it takes JavaScript code andexecutes it while
browsing in Chrome. It provides a runtime environment for the execution of JavaScript code. The
best part is that the JavaScript engineis completely independent of the browser in which it runs. This
is the feature that led Node.js designers to choose the V8 engine to power the framework, and the
rest is history. The V8 enginewas also utilized to construct desktop frameworks and databases as
Node.JS grew in popularity.

How does the V8 Engine works?


A JavaScript Engine is an interpreter that interprets JavaScript code and runs it. Thefirst way to
develop a JavaScript engine is to implement it as a standard interpreter, as done by Mozilla’s
SpiderMonkey. The other option isto employ Just-in-Time (JIT) compilation, which turns native
JavaScript codeto machine code as V8 does. The distinction between V8 code and other
programming languages is that it does not generate intermediate code.
The Ignition interpreter compiles JavaScript code and generates non- optimized machine code when
a developer or program runs it on V8 (i.e. in abrowser or Nodeenvironment). The Turbofan and
Crankshaft components ofV8 examine and recompile the machine code at runtime for optimal
performance.
Node.Js and V8
Node.js is referred to as a runtime environment since it contains everythingyou needto run a
JavaScript program.
This V8 engine is at the heart of Node.js. The diagram compares the Java Virtual Machine (JVM),
which is used to power the Java Runtime environment with the V8engine. The Node.js runtime
environment includes several Node APIs to power the Node.js environment in addition to the V8
engine. We can enhance the functionality of our node code by installing extranpm packages.

Relation between Node.Js and V8


One thing to keep in mind is that V8 is essentially a standalone C++ library that is utilized to run
JavaScript code by Node or Chromium. V8 exposes anAPI that otherapplications can utilize, so you
can embed V8 in your C++ program and run a JavaScript program from it. Node and Chrome work
in this manner.
Let’s say we want to add the ability to have statements like print(‘hello world’)inaddition to
console.log(‘Hello World’) in our JavaScript code. In V8, which is already open-sourced, we can
add our own C++ implementation of the print function.
Memory limit of V8 in Node.js
Currently, V8 has a RAM limit of 512MB on 32-bit computers and 1GB on 64-bit platforms by
default. This limit can be increased by setting –max-old- space-size to amaximum of ~1gb for 32-bit
and ~1.7gb for 64-bit systems. If you’re running out of memory, it’s a good idea to break your single
process into numerous workers.

Can Node.js work without V8?


V8 is required for the current Node.js engine to function. In the absence of V8, it wouldn’t have a
JavaScript engine, and thus wouldn’t be able to run JavaScript code. The V8 interface between C++
and JavaScript is used by
the native code bindings that come with Node.js, such as the fs (File System)moduleand the Net
module.
Although anything is possible in the tech world, and Microsoft attempted in July 2016 to replace the
V8 engine in Node.js with the Chakra JavaScript engine (whichwas used in Edge at the time), that
project never took off, andMicrosoft Edge recently switched to Chromium, which uses the V8
JavaScript engine.
DENO is the newest technology introduced in the domain of server-side programming. Many believe
it will be a Node.js replacement in the next 2-3years,and it is also powered by the V8 JavaScript
engine.

How V8 compiles JavaScript code

V8 is a high-performance, open-source JavaScript and WebAssembly engineused byGoogle Chrome


and Node.js. In this article, we will be going to see what happens behind the scene of V8
Architecture.
There are basically three steps involved in processing the code:
Parsing the code
Compiling the code
Executing the code
Now let’s understand each of these phases in depth.
Parsing Phase: During the parsing phase, the code is broken down into its respective tokens.
Compilation phase: Compilation is the process of converting human-readable code to machine
code. There are two ways to compile the code :
Using an Interpreter: The interpreter scans the code line by line andconverts it into byte code.
Example: Python
Using a Compiler: The Compiler scans the entire document andcompiles it into highly optimized
byte code. Example: Java
Execution Phase: The byte code is executed by using the Memory heapandthe Call Stack of the V8
engine’s runtime environment. Memory
Heap is the place where all the variables and functions are assigned memory. Call Stack is the place
where each individual functions, when called are pushed to the stack, and popped out after their
execution. When the interpreter interprets the code,using an object structure, where the keysare the
byte code and the values the functions which handle the corresponding byte code. The V8 engine
orders the values in the form of a list in memory, which is saved into a Map thereby saving a lot of
memory.
Example:
let Person = {name: "NRI INSTITUTE OF TECHNOLOGY"}
Person.age = 20;
In the above example, a map holds the Person object, which has the property name.The second line
creates a new object with the property age and links it back to the Person object. The problem with
the above approachis that it takes linear time to search through the linked lists. To combat the
problem, V8 has provided us with Inline Cache(IC).
Inline Cache: Inline Cache is a data structure used to keep track of the addressesof the properties on
objects, thereby reducing the lookup time. It tracks all the LOAD, STORE, and CALL events within
a function, by maintaining a FeedbackVector. Feedback Vector is simply an array used totrack all
the Inline Caches of aparticular function.
Example :
const sum = (a, b) => {
return a+b;
}

For the above example, the IC is :


[{ slot: 0, icType: LOAD, value: UNINIT}]
Here, the function has one IC with type LOAD and value UNINIT, whichmeans thatthe function has
not yet been initialized.
Upon Calling the function :
sum(5, 10)
sum(5, "NRI INSTITUTE OF TECHNOLOGY")
On the first call, the IC changes to:
[{ slot: 0, icType: LOAD, value: MONO(I) }]

Here the code is interpreted in a manner, where the arguments passed areonly ofinteger type. i.e the
function will only work for integer values.

On the second call, the IC changes to:


[{ slot: 0, icType: LOAD, value: POLY[I,S] }]

Here the code is interpreted in a manner, where the arguments passed caneither be of integer type or
string. i.e the function will work for both integers as well as strings. Thereby, the running time of the
function is faster if the type of arguments received is not modified. Inline caches keep track of
howfrequently they’re used and provide necessary feedback to the Turbofan compiler. The Compiler
takes the byte code and type feedback from the interpreter and tries to optimize the code andproduces
new byte code.

Suppose the compiler compiles a function assuming the data fetched from the APIcall is of type
String, the code fails when the data received is of typeobject. In thiscase, the compiler de-compiles
the code, falls back to the interpreter, and updates the feedback.
The Compilation and Execution of the JavaScript code go hand in hand.
Below is the diagrammatic representation of the compilation of JavaScript code.

The V8 engine tries to free up the memory heap, by clearing out unusedfunctions,clearing out
timeouts, clearing out intervals, etc.
Now, let’s understand the process of Garbage Collection.
Garbage Collection: It is an important aspect of programming and the techniques used by the
garbage collector have improved the latency, page load, pause times, etc.The V8 engine is provided
with the Orinoco GarbageCollector which internally uses the Mark and Sweep Algorithm to free up
space from the memory heap.
The Orinoco Garbage Collector uses three ways to collect the trash:
Parallel: In the parallel collection, the main JavaScript thread uses the help offew helper threads
parallelly to clear out the garbage, as a result,the main execution is stopped only for a while.
Incremental: In the incremental collection, the main JavaScript thread takes turns to collect the
garbage i.e in an incremental fashion. This typeof collectionis used to further reduce the latency of
the main thread. Example: The JavaScript thread first collects the garbage for some time and then
switches to the main execution for a while and then switches back to garbage collection. This process
goes on until the entire garbageis collected.
Concurrent: In the concurrent collection, the main JavaScript thread is notdisturbed and the entire
Garbage is collected by the helper threads inthe background.
EXPERIMENT-3
UNDERSTANDING NODE.JS

MEAN Stack is one of the most popular Technology Stack. It is used to develop a Full Stack
Web Application. Although it is a Stack of different technologies, all of these are based on JavaScript
language.
MEAN Stands for:
M – MongoDB
E – Express
A – Angular
N – Node.js

This stack leads to faster development as well as the deployment of the Web Application. Angular is
Frontend Development Framework whereas Node.js, Express, and MongoDB are used for Backend
development as shown in the belowfigure

Flow of Data in MEAN Stack Application: Here, each module communicateswith the others in order
to have a flow of the data fromServer/Backend to Client/Frontend.

Getting Started with each Technology with examples: The description ofeach Technology in this
Stack as well as the links to learn them are given below:
Node.js: Node.js is used to write the Server Side Code in Javascript. Oneof themost important points
is that it runs the JavaScript code outside the Browser. It is cross-platform and Open Source.

Pre-requisites to learn Node.js- JavaScript/TypeScript


Go to Node.js Downloads and click Download button to get thelatestversion and Install as per your
Operating System.
Verify whether it is installed correctly by checking the version:
node -v
If no version is obtained then it is not installed correctly.
Check the version of npm (It is installed by default with node):
npm -v
Create an index.js file inside your project folder and copy thefollowing code to it:
var http = require("http"); http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});

// Send the response text as "Hello World"response.end('Hello World\n');


}).listen(3100);

console.log('Server running at http://127.0.0.1:3100/');


Now open terminal and execute the following command:
node index.js
You will see on Terminal console a log which says:
Server running at http://127.0.0.1:3100/
Go to the browser and type the URL: http://127.0.0.1:3100/ you willseean output as below:

AngularJS: Angular is a Front-end Open Source Framework developed by Google Team. This
framework is revised in such away that backward compatibility is maintained (If there is any
breaking change then Angular informs it very early). Angular projects are simple to create using
AngularCLI (Command Line Interface) tool developed by the Angular team.
Pre-requisites to learn Angular:
TypeScript
CSS Preprocessor
Template Code (Angular Material, HTML 5, etc)
Installing Angular CLI – Command Line Interface using npm (NodePackage Manager)
npm install -g @angular/cli
Now check whether it was installed correctly using below command:
ng --version
It should show something like:

Now, create a new project using below command:


ng new project_name
Go to project Directory using below command:
cd project_name
Start the Angular Application using below command:
ng serve
Application will start on http://localhost:4200, you will see thefollowing:

Now make changes in app.component.html file and save the file, the application will reload
automatically and corresponding changes will be reflected.
MongoDB: MongoDB is a NoSQL Database. It has JSON like documents. It is document oriented
database.
Pre-requisites to learn MongoDB:
What is Database
Disadvantages of SQL Database
Creating a database:
use database_name;
Create a collection:
db.createCollection("first_collection");
Insert a record in the Collection:
db.first_collection.insertOne(
{name:"Geeks For Geeks"}
);
Print all the records in a collection:
db.first_collection.find()

ExpressJS: Express is a web Framework build on Node.js and used tomakeAPI and to build Web
Applications.
Pre-requisites to learn Express:
JavaScript/ TypeScript
Node.js
Initialize a Project by typing the following command on terminal:
npm init
It will ask some questions, Press enter in order to set all the defaultoptions. This will create
package.json file as shown below:
{
"name": "gfg-express",
"version": "1.0.0",
"description": "Basic Express Node.js Application","main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
}

Install the express using below command:


npm install express –save

Now, the package.json file will be changed to add thedependencies as shown below:

{
"name": "gfg-express",
"version": "1.0.0",
"description": "Basic Express Node.js Application","main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC","dependencies": {
"express": "^4.17.1"
}
}

Create index.js file and add the below code to it:


const express = require('express')const app = express()
const PORT = 3000

app.get('/', (req, res) =>


res.send('Hello World!'))

app.listen(PORT, () => console.log(


`Example app listening at http://localhost:${PORT}`))

Start the express server using below command:


node index.js
Go to http://localhost:3000 to see the output as below:
EXPERIMENT-4
Node.js HTTP Module

The Built-in HTTP Module

Node.js has a built-in module called HTTP, which allows Node.js to transferdata over the Hyper Text
Transfer Protocol (HTTP).

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

var http = require('http');


Node.js as a Web Server

The HTTP module can create an HTTP server that listens to server ports andgives a response back to
the client.

Use the createServer() method to create an HTTP server:

Example
var http = require('http');

//create a server object: http.createServer(function (req, res) {


res.write('Hello World!'); //write a response to the clientres.end(); //end the response
}).listen(8080); //the server object listens on port 8080output

The function passed into the http.createServer() method, will be executedwhen someone tries to access
the computer on port 8080.

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

Initiate demo_http.js:

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


If you have followed the same steps on your computer, you will see the sameresult as the example:
http://localhost:8080

Add an HTTP Header


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
var http = require('http'); http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');res.end();
}).listen(8080);
output

The first argument of the res.writeHead() method is the status code, 200means that all is OK, the
second argument is an object containing the response headers.

Read the Query String


The function passed into the http.createServer() has a req argument that represents the request from
the client, as an object (http.IncomingMessageobject).

This object has a property called "url" which holds the part of the url thatcomes after the domain name:

demo_http_url.js

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


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

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

Initiate demo_http_url.js:

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


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

http://localhost:8080/summer

Will produce this result:

/summer
output

http://localhost:8080/winter

Will produce this result:

/winter
output
Split the Query String
There are built-in modules to easily split the query string into readable parts,such as the URL module.

Example

Split the query string into readable parts:

var http = require('http');


var url = require('url');

http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'});var q =


url.parse(req.url, true).query;
var txt = q.year + " " + q.month;res.end(txt);
}).listen(8080);

Save the code above in a file called "demo_querystring.js" and initiate thefile:

Initiate demo_querystring.js:

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


The address: http://localhost:8080/?year=2017&month=July
Will produce this result:

2017 July
output

Node.js File System Module


Node.js as a File Server
The Node.js file system module allows you to work with the file system onyour 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 asNode.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) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});res.write(data);
return res.end();
});
}).listen(8080);
output

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


If you have followed the same steps on your computer, you will see the sameresult as the example:
http://localhost: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 doesnot exist, the file will be
created:

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!');
});
output

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!');
});

The fs.writeFile() method replaces the specified file and content if it exists. Ifthe 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!');
});

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 thespecified 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!');
});
output

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!');
});

Delete Files
To delete a file with the File System module, use the fs.unlink() method.The fs.unlink() method deletes
the specified file:
var fs = require('fs'); fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err; console.log('File deleted!');
});
output
Example
Delete "mynewfile2.txt":

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!');
});
output:
EXPERIMENT-5
Buffers and streams in Node.js
Buffer in Nodejs

In Nodejs we can manipulate these memory spaces with the modulecalled Buffer built into its core.
Buffers are widely used when working with binary data at the network level. Let us remember that
many of the Nodejs modules and functionalities work implicitly based on events and manipulation of
Buffer / Streams, such as the core File System or HTTP modules that store the temporary dataflow in
a Buffer.

Here are some important features of Buffers:

Buffers are stored in a sequence of integers.

Once created they cannot be resized.

Here is an example of creating a Buffer in Nodejs using the Bufferclass:

The code snippet above creates a Buffer containing the UTF-8 encoded bytes for the string “hello”,
this prints the following outputto the console:

const { Buffer } =
require('buffer');const buf6 =
Buffer.from('hello');

console.log(buf6);

Once the information is saved, we can perfectly read the storedcontent, here is an example:

Most of the programming languages have incorporated in their corea set of functionalities and classes
that allow you to work with Buffers and Streams in a simple way.

Stream in Nodejs

Nodejs has a module called stream that helps us with the manipulation of these flows, but depending
on the case we will usesome type of stream.

In general, there are 4 types of Streams in Nodejs:

Writable: Streams in which we can write data.

Readable: Streams receiving input data.

Duplex: Streams that are both read and written.

Transform: Streams that can modify or transform data asit is written and read.

If we have already worked with Nodejs before, surely we have noticed that, for example, any HTTP
server based on Nodejs, workswith reading Streams in the request to the server (Readable) and the
response to the client works with writing Streams (Writable). Thisand other core modules work in the
same way.

Here is an example of creating a stream in Nodejs of type readableand sending data:

const Stream = require('stream');


const readableStream = new Stream.Readable();

readableStream.push('Hello');
readableStream.push(' ');
readableStream.push('World');
readableStream.push(null);

async function getContentReadStream(readable) {


for await (const chunk of readable) {
console.log(chunk);
console.log(chunk.toString());
}
}

getContentReadStream(readableStream);

This prints the following output to the console:


<Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64>
Hello World

Emphasizing that when creating an object of type stream, a supportbuffer for manipulation is
automatically created. The size of the chunk or buffer can be previously configured.

Here is a complementary image of the Buffers and Streamsrelationship:

Events in Node.js
Every action on a computer is an event. Like when a connection is made or afile 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');
});

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 EventEmitterobject:

var events = require('events');


var eventEmitter = new events.EventEmitter();
The EventEmitter Object
You can assign event handlers to your own events with the EventEmitterobject.

In the example below we have created a function that will be executed whena "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');


EXPERIMENT-6
Express Overview
Express is a minimal and flexible Node.js web application framework that provides a robust set of
features to develop web and mobile applications. It facilitates the rapid development of Node based
Web applications. Following are some of the core features of Express framework

Allows to set up middlewares to respond to HTTP Requests.
Defines a routing table which is used to perform different actions based onHTTP Method and
URL.
Allows to dynamically render HTML Pages based on passing arguments totemplates.

Installing Express
Firstly, install the Express framework globally using NPM so that it can be used to create a web
application using node terminal.
$ npm install express --save
The above command saves the installation locally in the node_modules directory and creates a
directory express inside node_modules. You should install the following important modulesalong
with express −
body-parser − This is a node.js middleware for handling JSON, Raw, Text andURL encoded form data.
cookie-parser − Parse Cookie header and populate req.cookies with an objectkeyed by the cookie
names.
multer − This is a node.js middleware for handling multipart/form-data.
$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save
Hello world Example
Following is a very basic Express app which starts a server and listens on port 8081 for connection.
This app responds with Hello World! for requests to the homepage. For every other path, it will
respond with a 404 Not Found.

var express = require('express');


var app = express();

app.get('/', function (req, res) {


res.send('Hello World');
})

var server = app.listen(8081, function () {


var host = server.address().address
var port = server.address().port

console.log("Example app listening at http://%s:%s", host, port)


})
Save the above code in a file named server.js and run it with the following command.
$ node server.js
You will see the following output −
Example app listening at http://0.0.0.0:8081
Open http://127.0.0.1:8081/ in any browser to see the following result.

Request & Response


Express application uses a callback function whose parameters are request
and response objects.
app.get('/', function (req, res) {
// --
})

Request Object − The request object represents the HTTP request and has properties for the request
query string, parameters, body, HTTP headers, and soon.
Response Object − The response object represents the HTTP response that an Express app sends when
it gets an HTTP request.
You can print req and res objects which provide a lot of information related to HTTP requestand
response including cookies, sessions, URL, etc.

Basic Routing
We have seen a basic application which serves HTTP request for the homepage. Routing refersto
determining how an application responds to a client request to a particular endpoint, which is a URI
(or path) and a specific HTTP request method (GET, POST, and so on).
We will extend our Hello World program to handle more types of HTTP requests.
var express = require('express');
var app = express();

// This responds with "Hello World" on the homepage


app.get('/', function (req, res) {
console.log("Got a GET request for the homepage");
res.send('Hello GET');
})

// This responds a POST request for the homepage


app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');
})

// This responds a DELETE request for the /del_user page.


app.delete('/del_user', function (req, res) {
console.log("Got a DELETE request for /del_user");
res.send('Hello DELETE');
})

// This responds a GET request for the /list_user page.


app.get('/list_user', function (req, res) {
console.log("Got a GET request for /list_user");
res.send('Page Listing');
})

// This responds a GET request for abcd, abxcd, ab123cd, and so on


app.get('/ab*cd', function(req, res) {
console.log("Got a GET request for /ab*cd");
res.send('Page Pattern Match');
})

var server = app.listen(8081, function () {


var host = server.address().address
var port = server.address().port

console.log("Example app listening at http://%s:%s", host, port)


})

Save the above code in a file named server.js and run it with the following command.
$ node server.js
You will see the following output −
Example app listening at http://0.0.0.0:8081
Now you can try different requests at http://127.0.0.1:8081 to see the output generated byserver.js.
Following are a few screens shots showing different responses for different URLs.
Screen showing again http://127.0.0.1:8081/list_user
Screen showing again http://127.0.0.1:8081/abcd

Screen showing again http://127.0.0.1:8081/abcdefg

Serving Static Files


Express provides a built-in middleware express.static to serve static files, such as images, CSS,
JavaScript, etc.
You simply need to pass the name of the directory where you keep your static assets, to the
express.static middleware to start serving the files directly. For example, if you keep yourimages,
CSS, and JavaScript files in a directory named public, you can do this −
app.use(express.static('public'));
We will keep a few images in public/images sub-directory as follows −
node_modules
server.js
public/
public/images
public/images/logo.png

Let's modify "Hello Word" app to add the functionality to handle static files.
var express = require('express');
var app = express();

app.use(express.static('public'));

app.get('/', function (req, res) {


res.send('Hello World');
})

var server = app.listen(8081, function () {


var host = server.address().address
var port = server.address().port

console.log("Example app listening at http://%s:%s", host, port)

})
Save the above code in a file named server.js and run it with the following command.
$ node server.js
Now open http://127.0.0.1:8081/images/logo.png in any browser and see observe followingresult.

GET Method
Here is a simple example which passes two values using HTML FORM GET method. We aregoing to
use process_get router inside server.js to handle this input.

<html>
<body>

<form action = "http://127.0.0.1:8081/process_get" method = "GET">


First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name">
<input type = "submit" value = "Submit">
</form>

</body>
</html>

Let's save above code in index.htm and modify server.js to handle home page requests as wellas the
input sent by the HTML form.

var express = require('express');


var app = express();

app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( dirname + "/" + "index.htm" );

})

app.get('/process_get', function (req, res) {


// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})

var server = app.listen(8081, function () {


var host = server.address().address
var port = server.address().port

console.log("Example app listening at http://%s:%s", host, port)


})
Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate thefollowing
form −

First
Name:
Last
Name:

Now you can enter the First and Last Name and then click submit button to see the result andit should
return the following result −
{"first_name":"John","last_name":"Paul"}

POST Method
Here is a simple example which passes two values using HTML FORM POST method. We aregoing to
use process_get router inside server.js to handle this input.
<html>
<body>

<form action = "http://127.0.0.1:8081/process_post" method = "POST">


First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name">
<input type = "submit" value = "Submit">
</form>

</body>
</html>

Let's save the above code in index.htm and modify server.js to handle home page requests aswell as
the input sent by the HTML form.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

// Create application/x-www-form-urlencoded parser


var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( dirname + "/" + "index.htm" );
})

app.post('/process_post', urlencodedParser, function (req, res) {


// Prepare output in JSON format
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})

var server = app.listen(8081, function () {


var host = server.address().address
var port = server.address().port

console.log("Example app listening at http://%s:%s", host, port)


})
Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate thefollowing
form –
First
Name:
Last
Name:

Now you can enter the First and Last Name and then click the submit buttonto see the followingresult −
{"first_name":"John","last_name":"Paul"}

File Upload

<html>
<head>
<title>File Uploading Form</title>
The following HTML code creates a file uploader form. This form has method attribute setto POST
and enctype attribute is set to multipart/form-
data
</head>

<body>
<h3>File Upload:</h3>
Select a file to upload: <br />

<form action = "http://127.0.0.1:8081/file_upload" method = "POST"


enctype = "multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type = "submit" value = "Upload File" />
</form>

</body>
</html>
Let's save above code in index.htm and modify server.js to handle home page requests as wellas file
upload.
var express = require('express');
var app = express();
var fs = require("fs");

var bodyParser = require('body-parser');


var multer = require('multer');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}));

app.get('/index.htm', function (req, res) {


res.sendFile( dirname + "/" + "index.htm" );
})

app.post('/file_upload', function (req, res) {


console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = dirname + "/" + req.files.file.name;

fs.readFile( req.files.file.path, function (err, data) {


fs.writeFile(file, data, function (err) {
if( err ) {
console.log( err );
} else {
response = {
message:'File uploaded successfully',
filename:req.files.file.name
};
}

console.log( response );
res.end( JSON.stringify( response ) );
});
});
})

var server = app.listen(8081, function () {


var host = server.address().address
var port = server.address().port

console.log("Example app listening at http://%s:%s", host, port)


})
Accessing the HTML document using http://127.0.0.1:8081/index.htm will generate thefollowing
form −
File Upload:
Select a file to upload:

NOTE: This is just dummy form and would not work, but it must work at your server.

Cookies Management
You can send cookies to a Node.js server which can handle the same using the following
middleware option. Following is a simple example to print all the cookies sent by the client.

var express = require('express')


var cookieParser = require('cookie-parser')

var app = express()


app.use(cookieParser())

app.get('/', function(req, res) {


console.log("Cookies: ", req.cookies)
})
app.listen(8081)
Experiment-7
Working with model, views and routes
Model – It can handle the database
View – It can handle the client-side web pages
Route- It can be execute the
dynamic web pages.
Model- In this folder, you can write thefunctionality & logics related to the Database like insert, fetch,
update, delete queries. Even It takes the query request from the controller & sends the response back to the
controller.

You can create a model in


the myappapplication through thefollowing steps

Create a folder models in thethe myappapplication.


Create a file crud-model.js in the models. Even you can createmore controller files.
Define some functionality in
the crud-model.jsas the followingscript
File Path- models/crud-model.jsFile Name – crud-model.js

module.exports={ createCrud:function(){
data="Form data was inserted";return data;
},
fetchCrud:function(){ data="data
was fetched";return data;
},
editCrud:function(editData){
data= "Data is edited by id: "+editData;
return data;
},
UpdateCrud:function(updateId){
data= "Data was updated by id: "+updateId;
return data;
},
deleteCrud:function(deleteId){
data= "Data was deleted by id: "+deleteId;
return data;
}
}
Include model file crud-model.js in the controller file crud-controller.jsof controllers using the following
script.
var crudModel=require('../models/crud-model');

Express – View

View- In this folder, you can write HTML code for displaying a web page on the web browser. Even you
can send the data from the controller to view for displaying data dynamically.

The view will be generated with the Basic Structure of Express App and It contains viewsfolder

You can create web pages in the viewsfolder through thefollowing steps
create a file crud-operation.ejsinthe viewsfolder.
write the HTML code as the followingscript. Even you can create another

HTML file & write HTML code based


on your project requirement.
File Name – crud-operation.ejs

<!DOCTYPE html>
<html>
<head>
<title>CRUD Operation</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<style> table, td,
th {
border: 1px solid #ddd;text-
align: left;}
table {
border-collapse: collapse;width:
50%;}
.table-data{ position:
relative;left:150px;
top:100px;}
th, td { padding:
15px;}
</style>
</head>
<body>
<% if(typeof editData!='undefined'){ %>
<h1><%= editData %></h1>
<form method="POST" action="/crud/edit/<%=editId %>">
<input type="submit" value="Update Data">
</form>

<% } else{ %>


<h1>Crud Operation</h1>
<h3>This is View Page</h3>
<h4>Create Data</h4>
<form method="POST" action="/crud/create">
<input type="submit" value="Create Data">
</form>
<% } %>
<br><br> <br><br>
<table border="1" >
<tr>
<th><a href="/crud/form">Crud Form</a></th>
<th><a href="/crud/fetch">Fetch Data</a></th>
<th><a href="/crud/edit/5">Edit Data</a></th>
<th><a href="/crud/delete/5">Delete Data</a></th>
</tr>
</table>
</body>
</html>

You can load a view file crud- operation.ejsin the controllerfile crud-controller.js of the
controllers’ folder using the following
script.

res.render('crud-operation');

Route – In the route folder, you can create a custom route/link to executethe dynamic web pages.

The Route will be generated with theBasic Structure of Express App and Itcontains routesfolder

You can create routes in


the routesfolder through thefollowing steps
Create a file crud-route.jsinthe routesfolder.
Define some functionality in
the crud-route.jsas the followingscript

Path – routes/crud-route.jsFile Name – crud-route.js


You have to load a route file crud- route.ejsin the root file app.js ofthe myapp app using the following
script.

var express = require('express');


var crudController=require('../controllers/crud-controller');
var router = express.Router();
// curd form route
router.get('/form', crudController.crudForm );
// create data route
router.post('/create', crudController.createCrud);
// display data route
router.get('/fetch', crudController.fetchCrud);
// edit data route
router.get('/edit/:id', crudController.editCrud);
// update data route
router.post('/edit/:id', crudController.UpdateCrud);
// delete data route
router.get('/delete/:id', crudController.deleteCrud);
module.exports = router;

var crudRouter = require('./routes/crud-route');app.use('/crud',


crudRouter);
EXPERIMENT-8
Working with MongoDB

There’s a bunch of GUIs (Graphical User Interface) to work with MongoDB server such as MongoDB
Compass, Studio 3Tand so on.
They provide a graphical interface so you can easily work withyour database and perform queries instead
of using a shell andtyping queries manually.

But in this article we’ll be using command prompt to do ourwork.

Now it’s time for us to dive into MongoDB commands that’llhelp you to use with your future projects.

Open up your command prompt and type mongod to start theMongoDB server.
Open up another shell and type mongo to connect toMongoDB database server.
Finding the current database you’re in
Db

This command will show the current database you are in. test isthe initial database that comes by default.
Listing databases
show databases
I currently have four databases. They are: CrudDB, admin, config and local.
Go to a particular database
use <your_db_name>

Here I’ve moved to the local database. You can check this if youtry the command db to print out the
current database name.
Creating a Database
With RDBMS (Relational Database Management Systems) wehave Databases, Tables, Rows and
Columns.
But in NoSQL databases, such as MongoDB, data is stored inBSON format (a binary version of JSON).
They are stored instructures called “collections”.
In SQL databases, these are similar to Tables.
Alright, let’s talk about how we create a database in the mongoshell.

use <your_db_name>
Wait, we had this command before! Why am I using it again?!

In MongoDB server, if your database is present already, usingthat command will navigate into your
database.

But if the database is not present already, then MongoDB serveris going to create the database for you.
Then, it will navigate into it.

After creating a new database, running the show


database command will not show your newly created database.This is because, until it has any data
(documents) in it, it is notgoing to show in your db list.
Creating a Collection
Navigate into your newly created database withthe use command.
Actually, there are two ways to create a collection. Let’s seeboth.

One way is to insert data into the collection:


db.myCollection.insert({"name": "john", "age" : 22, "location": "colombo"})
This is going to create your collection myCollection even if thecollection does not exist. Then it will insert
a document
with name and age. These are non-capped collections.The second way is shown below:

Creating a Non-Capped Collection


db.createCollection("myCollection")
Creating a Capped Collection
db.createCollection("mySecondCollection", {capped : true, size
: 2, max : 2})
In this way, you’re going to create a collection without insertingdata.
A “capped collection” has a maximum document count thatprevents overflowing documents.
In this example, I have enabled capping, by setting its valueto true.
The size : 2 means a limit of two megabytes, and max: 2 sets themaximum number of documents to two.
Now if you try to insert more than two documents
to mySecondCollection and use the find command (which we will talk about soon), you’ll only see the
most recently inserteddocuments. Keep in mind this doesn’t mean that the very first document has been
deleted — it is just not showing.
Inserting Data
We can insert data to a new collection, or to a collection that hasbeen created before.
ways data can be stored in a JSON
There are three methods of inserting data.
insertOne() is used to insert a single document only.
insertMany() is used to insert more than one document.
insert() is used to insert documents as many as you want.Below are some examples:
insertOne()
db.myCollection.insertOne(
{
"name": "navindu","age": 22
}
)
insertMany()
db.myCollection.insertMany([
{
"name": "navindu","age": 22
},
{
"name": "kavindu","age": 20
},

{
"name": "john doe","age": 25,
"location": "colombo"
}
])
The insert() method is similar to the insertMany() method. Also, notice we have inserted a new property
called location onthe document for John Doe. So if you use find, then you’ll see only for john doe the
location property is attached.
This can be an advantage when it comes to NoSQL databasessuch as MongoDB. It allows for scalability.

Successfully inserted data


7. Querying Data
Here’s how you can query all data from a collection:db.myCollection.find()
result
If you want to see this data in a cleaner, way just add .pretty() tothe end of it. This will display document
in pretty-printed JSONformat.
db.myCollection.find().pretty()

result
Wait...In these examples did you just notice something like _id?How did that get there?
Well, whenever you insert a document, MongoDB automaticallyadds an _id field which uniquely
identifies each document. If you do not want it to display, just simply run the following command
db.myCollection.find({}, _id: 0).pretty()Next, we’ll look at filtering data.

If you want to display some specific document, you could specify a single detail of the document which
you want to bedisplayed.
db.myCollection.find(
{
name: "john"
}
)

result
Let’s say you want only to display people whose age is less than
25. You can use $lt to filter for this.db.myCollection.find(
{
age : {$lt : 25}
}
)
Similarly, $gt stands for greater than, $lte is “less than or equalto”, $gte is “greater than or equal to” and
$ne is “not equal”.
Updating documents
Let’s say you want to update someone’s address or age, how youcould do it? Well, see the next example:
db.myCollection.update({age : 20}, {$set: {age: 23}})
The first argument is the field of which document you want to update. Here, I specify age for the
simplicity. In production environment, you could use something like the _id field.
It is always better to use something like _id to update a uniquerow. This is because multiple fields can
have
same age and name. Therefore, if you update a single row, itwill affect all rows which have same name
and age.

result
If you update a document this way with a new property, let’s say location for example, the document will
be updated with thenew attribute. And if you do a find, then the result will be:

result
If you need to remove a property from a single document, you could do something like this (let’s say you
want age to be gone):db.myCollection.update({name: "navindu"}, {$unset: age});
Removing a document
As I have mentioned earlier, when you update or delete adocument, you just need specify the _id not
just name, age, location. db.myCollection.remove({name: "navindu"});
Removing a collection
db.myCollection.remove({});
Note, this is not equal to the drop() method. The difference
is drop() is used to remove all the documents inside a collection,but the remove() method is used to delete
all the documents along with the collection itself.
Logical Operators
MongoDB provides logical operators. The picture belowsummarizes the different types of logical
operators.
EXPERIMENT-9
GETTING START WITH ANGULAR:
What is AngularJS?

AngularJS is a client side JavaScript MVC framework to develop a dynamic web application. 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 is also called just "Angular".
AngularJS changes static HTML to dynamic HTML. It extends the ability of HTMLby adding built-in
attributes and components and also provides an ability to create custom attributes using simple
JavaScript.

AngularJS website - https://angularjs.org

AngularJS Example:
<!DOCTYPE html>

<html>
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app>
Enter Your Name: <input type="text" ng-model="name" /> <br />Hello <label ng-bind="name"></label>
</body>
</html>
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 tocreate Single Page Applications.
Prerequisites

Basic knowledge of HTML, JavaScript, CSS and web application is required.


EXPERIMENT-10
INTRODUCTION TO COMPONENETS
What’s a component?

A component is basically a directive that uses a simpler configuration and that is suitable for a
component-based architecture, which is what Angular 2 is all about. Think of a component as a widget: A
piece of HTML code that you can reuse in several different places in your webapplication.

Why Use Components

Reduce duplication: Traditionally, if the same UI component had to be present in two differentplaceson a
page (let alone two different pages in the application), the HTML code had to be duplicated. This leads to
not only an increase in code duplication but also a decrease in
maintainability, making it painful to keep the UI consistent. Components serve as a simplesolution to this
problem.
HTML bundled with logic: Under the MVC architecture, having separate files for HTML tagsand the
controller logic may seem organized but has a downside — there is no clear way of showing which
HTML content is changed or generated which part of the controller logic.
Bundling both these into a single component makes it cleaner to understand their relationshipwhile also
ensuring that one does not get changed without considering the other part.

Consistent UI: Components also offer great help in making sure the design across the application is
consistent. By enabling reusable HTML code, this practice forces you to keep yourelements uniform
wherever they are used.
Create a component

Let’s build a simple “Hello World ” component to illustrate how easy it is. The end goal for our
component will be to display this simple piece of HTML:

<span>Hello World!</span>

The syntax to create a component is fairly easy. All you have to do is declare its name and passa config
object that specifies what your component should do. In our case, it will render some basic HTML:

angular.module("myApp", [])
.component("helloWorld",{
template: 'Hello World!'
});

In order to then use that component in our code, all we need is this:
<div ng-app="myApp">
<hello-world> </hello-world>
</div>

TEMPLATES,INTERPOLATION AND DIRECTIVES:

TEMPLATES:

Templates in AngularJS are simply HTML files filled or enriched with AngularJS stuff like
attributes and directives. A directive is a marker element that is used to target a particular
attribute or class to render its behavior according to the needs. Model and controller in Angular are
combined with the templates to manipulate the view the user sees in his/her browser. Angular
templates can also accommodate CSS, Form controls, Filters, and Expressions. There are two types
of templates:
Static Template
Dynamic Templates

Interpolation:

In AngularJS, Interpolation is a way to transfer the data from a TypeScript code to an HTML template
(view), i.e. it is a method by which we can put an expression in between some text and get the value
of that expression. Interpolation basically binds the text with the expressi on value. Interpolation is a one-
way data binding. Through this, we can bind some data values from our logic. To use the interpolation
we need to put our expression into the double curly braces {{ }}. With Interpolation, only string data/
expression will be evaluated, ie., only string parameter will be used in the interpolation.

DIRECTIVES:

Directives are markers on the DOM element which tell AngularJS to attach a specified behavior to that
DOM element or even transform the DOM element with its children. Simple AngularJS allows extending
HTML with new attributes called Directives. AngularJS has a setof built-in directives whichoffers
functionality to the applications. It also defines its own directives. A directive can be defined using some
functions which are: Element name, Attribute, Class, and Comment.

You might also like