Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

WebDevelopment BackEnd

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

*NodeJS Server*

➢ Node.JS:
• A server-side platform which is built on Google Chrome’s V8-JavaScript
Engine which was initially built and developed by Mr. Rayn Dal in the year
2009.
• Using Node.js we could able to build faster and scalable network
applications.
• Node.js internally uses event driven and non-blocking I/O mechanism (or)
model which makes it light weight and efficient for data intensive real time
applications which run on distributive system/devices.
• Node.js is open source and cross-platform runtime environment using which
we could develop server side and networking-based applications.
• JavaScript is programming language using which we could able to add
instructions within Node.js.
• Node.js comes with rich library of various JavaScript modules which
simplifies the development of the web applications using Node.js.
• Node.js is a combination of Run-Time environment and JavaScript library.
➢ Features of Node.JS used for developing web applications:
➢ Asynchronous and Event Driven:
All API’s of Node.js are asynchronous and non-blocking which means
it is a server which doesn’t waits for any API to return the data, the server
moves to the next API after calling it, a notification mechanism of events of
Node.js helps server to get response from previous API calls.
➢ Faster in Processing:
As the Node.js is built on Google Chrome’s V8-JS Engine, it is very
faster in executing instructions.
➢ Single Threaded but Highly Scalable:
Internally Node.js uses a single threaded model with event looping, the
event mechanism helps the server to respond in a non-blocking way and makes
the server highly scalable.

1|Page
Naresh i®technologies Mr Durga Prasad.P
➢ No Buffering:
Node.js applications never buffer any data, these applications output
data in chunks.
➢ Architecture of Node.JS:

2|Page
Naresh i®technologies Mr Durga Prasad.P
➢ Node Package Manager (NPM):
• NPM is an online code repository publishing of open source Node.js code, it
is also a command line utility for interacting with NPM repository for
package installing and version management.
• It is through NPM we could work with installation (or) uninstallation (or)
upgradation node modules. Through NPM we could even start or stop node
server.
➢ Node.js Module:
A module in node.js is a simpler or complex functionality organized in
single or multiple JavaScript files which can be reserved throughout the
node.js application. Each module in node.js has its own context so that it
doesn’t interfere with other modules or doesn’t interrupt the global scope.
It is through NPM we install (or) uninstall version manager of any
module can be done.
Following are the basic steps which we need to create a HTTP Node
Server,
Step-1: Download Node HTTP Module through NPM,
npm install http //Downloads a HTTP Module.
Step-2: Create a JavaScript file and include HTTP Module through require
method.
var http = require(“http”); //including a Node Module.
Step-3: Use “createServer” method under HTTP, which takes a callback method
as a parameter with default request and response objects.
http.createServer ( (req,res) => {
….. //Code to handle request and response
});
Step-4: Using response object we can specify the type of content being returned
from the server.
res.writeHead(200,{‘content-type’: ‘text/HTML’});

3|Page
Naresh i®technologies Mr Durga Prasad.P
Using writeHead method we can specify the response status code along
with the response text type.
Step-5: using res.write() method we can write the content to be responded from
the server.
res.write(“<Content>”);
Step-6: res.end() is an predefined method through which we can send request
using user response.
res.end();
Step-7: Make the server to listen at a particular port number
server.listen(8080);

➢ Performing Node Operations in Node.js through fs module:


“fs” is a predefined node module through which we could able to
perform read, write and append operations or any file. Following are the steps
to be followed while making use of FS module,
Step-1: Download fs Module through NPM

4|Page
Naresh i®technologies Mr Durga Prasad.P
npm i fs
Step-2: Include and create a reference for FS Module,
var fs = require(“fs”);
Step-3: Use the following predefined methods under FS Module through
which we could able to do any file operations in files.
Fs.readFile(“<filename>”, (err,data) => {
//err objects holds the error if any while reading file
//Data holds the actual data of file.
});
Fs.appenFile(“<filename>”, “<Content to be written>”,(err,data) => {
//err objects holds the error if any while reading file
//Data holds the actual data of file.
});
Fs.rename(“filename”,”newfileName”,(err) => {
Err……
});
Ex:

5|Page
Naresh i®technologies Mr Durga Prasad.P
➢ Node Express.JS Framework:
Express.js is a web application framework for node.js through which
we could able to create flexible node.js web applications. It is one of the most
popular web frameworks provides following mechanisms,

• It writes handlers with requests with different http at different URL paths.
• It integrates with view rendering engines in order to generate response by
inserting data into the template.
• It sets common web applications settings like the port to use for connecting,
location of templates that are used etc.…
• Express itself is fairly minimalist developers are created compatible
middleware packages to address utmost any web development problems.
• There are libraries to work with cookies, sessions, user logins, URL
params, post data, security headers and so on.
• Express was released on 2010 and current latest version is 4.17.1*.
➢ Folder structure got created through express generator:
• Node_modules:
Under which all the downloaded node modules of the current app will be
stored. This folder name cannot be renamed.
• Package.json file:
It holds a json object with all the configuration information of the current
module.
i. It holds list of dependencies of node module.
ii. Name and Version number of the current application.
iii. Author name and contact details.
iv. Starting point of the current application (node start/server start).
• Bin Folder:
A predefined folder holds a predefined ‘www’ holds the set of instructions
through which we could create http server, making the server to listen a
default port number handling the errors if any.
6|Page
Naresh i®technologies Mr Durga Prasad.P
o Bin folder and www file name can be renamed to a custom name,
corresponding changes to be done at package.json
• Routes Folder:
Holds set of JavaScript files, where each JavaScript file represents a single
web service. Any number of web services can be added with in node
server, all the web services JS files should be placed under the Routes
folder.
o Index.js, users.js are the default services available under routes
folder.
o Once the services are added under routes folder, corresponding route
mapping or URL mapping has to be done under app.js file.
• Steps to create a web service under a node express server:
Step-1: Create an external JS file under Routes Folder.
Step-2: under the JS file, create an instance of express module.
Var express = require(‘express’);
Step-3: create a router instance through a router class under express
module.
Var router = express.Router();
Step-4: using the router reference, through GET/POST method add the
business logic of the corresponding webservice under call back method.
router.get(“/”, (req,res) => {
….. //Logic
res.send();
});
(or)
router.get(“/”, (req,res) => {
….. //Logic
res.send();
});
Step-5: under the app.js file specify the router path through which web
services can be accessible.

7|Page
Naresh i®technologies Mr Durga Prasad.P
Ex:

The file which is inside


the Router

JS File

8|Page
Naresh i®technologies Mr Durga Prasad.P
9|Page
Naresh i®technologies Mr Durga Prasad.P
*Mongo DB*
➢ MongoDB:
MongoDB is a cross-platform document-oriented database program
classified as a NOSQL database program. MongoDB uses JSON like
documents with optional schemas. MongoDB is developed by MongoDB.INC
and licensed under the server-side public license. MongoDB is a document
data base with the scalability and flexibility that you want with the querying
and indexing that you need.
➢ Key Features of MongoDB:
• Supports ad hoc queries:
In MongoDB you can search by field, range query and it also supports
regular expression searches.

• Indexing:
You can index any field in a document.

• Replication:
MongoDB supports slave replication. A master can perform read and write
and a slave copies data from the master and can only be used for reads or
backup (not writes).

• Duplication of data:
MongoDB can run over multiple servers. The data is duplicated to keep the
system up and keep its running condition in case of hardware failure.

• Load Balancing:
It has an automatic load balancing configuration because of the data placed
in shards.

• Supports Map reduce and aggregation tools.


• Uses JavaScript instead of procedures.
• It is a schema less DB written in C++.
• Provides high performance.
• Stores files of any size easily without complicating your stack.

10 | P a g e
Naresh i®technologies Mr Durga Prasad.P
• Easy to administer in case of failures.
• It also supports:
o JSON data model with dynamic schemas.
o Auto-Sharing for horizontal scalability.
o Built in replication for high availability.
o Now a days many companies using MongoDB to create new types
of applications, improve performance and availability.
➢ Difference between MongoDB Structure and SQL Structure:

11 | P a g e
Naresh i®technologies Mr Durga Prasad.P
➢ Commands that can be run on a Mongo Shell:
• db – returns the name of current database been used.
• use<db name> - switches to specific DB.
• db.help( ) – throws help commands.
• Show dbs – throws list of all database under MongoDB.
• Show users – returns the list of users.
• db.getCollectionNames( ) – shows list of collections within a DB.
• db.createCollection(“<Collection Name>”) – used to create a collection.
Ex: db.createCollection("Login_Details")
• db.collection.insert({document}) – used to insert a document to a
collection.
• db.collection.insertmany([<document1>,<document2>,…] – used to
insert many document to a single collection.
Ex:
db.Login_Details.insertMany([{_id:'adminLogin',uid:'admin',upsw:'admin'},
{_id:'studentLogin',uid:'student',upsw:'student'},{_id:'parentLogin',uid:'paren
t',upsw:'parent'}])

• db.collection.find({key:’value’}) – used to find a specific document from


a collection.
• db.collection.update(<query>,<updatedDocument>).
• db.collectionName.remove() – to delete a collection from database.
• Use - used to create a database or to switch to an existing data base.
➢ Creating connection to MongoDB through Node.js:
Step-1: Download and install MongoDB Node Module.
npm install mongodb - - save
Here –save is used to save in package.json
Step-2: Include MongoDB and create instance for mongo client.
Ex:var mongodb = require(“mongodb”).MongoClient;
Step-3: Create URL with MongoDB protocol, server name and port number
it is running.
Ex: var URL = ‘mongodb://localhost:27017/’;
12 | P a g e
Naresh i®technologies Mr Durga Prasad.P
Step-4: create a connection to MongoDB through mongo client by passing the
MongoDB URL.
mongoClient.connect( mongodbURL, ( err, client ) => {
//Client object through which we get connected to the specific DataBase
});
Step-5: Through client object we could able to connect to the specified
database under the MongoDB.
Ex: var db = client.db(“DataBaseName”);
Step-6: Through db object we could get reference to required collection using
db.collection( ) method.
Ex: var collection = db.collection(“Collection Name”);
Step-7: add the required command.
Ex: collection.find(‘’).toArray((error,list)=> {
… …
});
Ex: Finding Data in the server,

13 | P a g e
Naresh i®technologies Mr Durga Prasad.P
➢ REST:
An API is always needed to create mobile applications, single page
applications, use AJAX calls and provide data to clients. An popular
architectural style of how to structure and name these APIs and the endpoints
is called REST (Representational Transfer State). HTTP 1.1 was designed
keeping REST principles in mind. REST was introduced by Roy Fielding in
2000 in his Paper Fielding Dissertations.
RESTful URIs and methods provide us with almost all information we
need to process a request. The table given below summarizes how the various
verbs should be used and how URIs should be named.
➢ Session:
• A session is time between login to logout. There are N number of node
modules been supported through which we can implement sessions in any
application.
• Express-session is one of the predefined modules through which we can
implement sessions within node express server.
• Following are the steps to be followed in order to implement sessions
through express-session in node module,
Step-1: Download and install express-session module.
npm install express-module
Step-2: Include express-session module in app.js module.
var session = require(“express-session”);
Step-3: Instantiate the session object by passing secret key, Cookie status
etc…
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))
Force the session identifier cookie to be set on every response. The
expiration is reset to the original maxAge, resetting the expiration
countdown.

The default value is false.

With this enabled, the session identifier cookie will expire


in maxAge since the last response was sent instead of in maxAge since the
session was last modified by the server.

14 | P a g e
Naresh i®technologies Mr Durga Prasad.P
Step-4: After the above steps, under each request object a session object will
exist to which we can inject required data and validate.
➢ Password Encryption in JavaScript:
JavaScript implementations of standard and secure cryptographic
algorithms
CryptoJS is a growing collection of standard and secure cryptographic
algorithms implemented in JavaScript using best practices and patterns. They
are fast, and they have a consistent and simple interface.
Step-1: To get encrypt your data first you should install node module for
Crypto.
npm install crypto-js –save
Step-2: Load Encrypt library,
const CryptoJS = require(“crypto-js”);
Step-3: Create a Secret Key,
var key = ‘SecretKey’
Note: This secret key is used to encrypt and to decrypt the code.
Step-4: Now, after defining the secret key perform the encryption by using
the key and the algorithm. Here we using AES algorithm to encrypt/decrypt
the data.
// (C) ENCRYPT
var cipher = CryptoJS.AES.encrypt("PASSWORD", key);
cipher = cipher.toString();
console.log(cipher);
Step-5: After the encryption the data which comes from the server is also
displayed in the encrypted format. So, to get the actual data we should decrypt
the data and show to the end user.
// (D) DECRYPT
var decipher = CryptoJS.AES.decrypt(cipher, key);

15 | P a g e
Naresh i®technologies Mr Durga Prasad.P
decipher = decipher.toString(CryptoJS.enc.Utf8);
console.log(decipher);
Note: Here we using AES algorithm to encrypt/decrypt the data. The Advanced
Encryption Standard (AES) is a U.S. Federal Information Processing Standard
(FIPS). It was selected after a 5-year process where 15 competing designs were
evaluated. CryptoJS supports AES-128, AES-192, and AES-256. It will pick the
variant by the size of the key you pass in. If you use a passphrase, then it will
generate a 256-bit key.

➢ Socket.IO:
Socket.IO is a library that enables real-time, bidirectional and event-
based communication between the browser and the server.

• Steps to establish real-time Connection:


Step-1: Install Socket.IO Node Module,
 npm install socket.io
Step-2: Open the app.js File and Load the module,
 var app = express( );
const server = require( ‘http’ ).Server( app );
const io = require( ‘server’ )( server );

16 | P a g e
Naresh i®technologies Mr Durga Prasad.P
Step-3: Check weather the connection is established or not,
 var count = 0; // to check the number of userconnected
io.on( ‘ connection ’, ( socket ) => {
count++;
console.log(‘A user is connected’ + count);
socket.on( ‘ disconnect’ , ( ) => {
count--;
console.log(‘A user is disconnected’ + count);
});
});
Step-4: In order to connect to the socket.io we are using an external API,
https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.2.0/socket.io.js
Step-5: Create an instance to the external API,
 const socket = io ( ‘ http://localhost:8081 ’ );
Step-6: Send the message to the server by using socket.emit,
 socket.emit( ‘ sendMessage’ , msg );
//sendMessage is the key and msg is the value.
Step-7: Receive the message from the client,
 socket.on( ‘sendMessage’, ( msg ) => {
//here sendMessage is the which we have given in client side
Socket.broadcast.emit( ‘recMsg’ , msg );
//here recMsg is the key and msg is the value which is used to
broadcast the message using broadcast.emit.
});
Step-8: Receive the data from the server which is going to broadcast,
 socket.on ( ‘recMsg’, (msg) => { addMessage ( msg, true ); } );

17 | P a g e
Naresh i®technologies Mr Durga Prasad.P
Ex:

Two Users are Connected

No active users.

18 | P a g e
Naresh i®technologies Mr Durga Prasad.P
➢ Clustering:
Clustering refers to a group of servers working together on one system
to provide users with higher availability. Using clusters, we can reduce the
DOM time and outages by allowing another server to take over the event of
an outage.
Clusters work like a group of servers connected to single system the
moment the server experience a server outage, the work load is redistributed
to server to another server before any down time is experienced.
➢ Steps to implement cluster:
Step-1: Create and install OS Module.
const os = require(“os”);
const cpuCount = os.cpus().length;
Step-2: Download and install cluster module.
Step-3: Include the cluster module through require module.
var cluster = require(“cluster”);
Step-4: cluster.fork is a predefined method through which we can have a
cluster copy of existing server.
Step-5: We can create a cluster copy only for the master cluster instance which
can be checked through “cluster.isMaster” property.

19 | P a g e
Naresh i®technologies Mr Durga Prasad.P
O/P:

➢ Uploading Files to the Server:


Multer is a node.js middleware for handling multipart/form-data, which is
primarily used for uploading files. It is written on top of busboy for maximum
efficiency.
Steps to upload file:
Step-1: Install multer Node Module.
npm install multer –save
Step-2: Multer adds a body object and a file or files object to the request object.
The body object contains the values of the text fields of the form,
the file or files object contains the files uploaded via the form.

Basic usage example:

Don't forget the enctype="multipart/form-data" in your form.

Step-3: Create a variable and assign upload file,


var uploadingFile = $(‘input[name=files]’)[0].files[0];
Step-4: Get the file size by using $(‘input[name=files]’)[0].files[0].size;

20 | P a g e
Naresh i®technologies Mr Durga Prasad.P
Step-5: To get the extension of the uploaded File,
var uploadingFile = $(‘input[name=files]’)[0].files[0];
var fileSize = uploadingFile.name.replace(/.*\./,’’);
Step-6: By using the Step-4 and Step-5 we can restrict the file size and type of
file that to be uploaded,

Step-7: Add FormData, The FormData interface provides a way to easily


construct a set of key/value pairs representing form fields and their values, which
can then be easily sent using the XMLHttpRequest.send() method. It uses the
same format a form would use if the encoding type were set to "multipart/form-
data".

Here, “files” is the key which we given the name in the input form file at Step-
2, and uploaded file contains the file which is going to be uploaded.
Step-8: Create an upload request from the client side,

21 | P a g e
Naresh i®technologies Mr Durga Prasad.P
Step-9: Go to the Routes and create an instance for multer and path,
var multer = require(‘multer’);
var path = require(‘path’);
Step-10: Read file from the disk, The disk storage engine gives you full control
on storing files to disk.

Step-11:

22 | P a g e
Naresh i®technologies Mr Durga Prasad.P

You might also like