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

Unit 3 1

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

Unit-3

Node is a Java script run time built on chrome v8 java script engine
 Node Js an Open source server environment
 Node Js is Free Source
 Node Js able to run javascript outside of the browser
 So node js uses javascript on the server

V8 developed in c++ . so c++ bindings play the key roll


JAVA SCRIPT FILE (Node C++
Js)
fs.readfile() Some c++ function
Os.platForm() Some c++ function

 Node Js is java script on server

Installing node.js and visual studio:


Step1: go to nodejs.org download latest version

Step2: Now go to terminal type node -v through we find node version and
installation conformation
NPM is node package manager is used install various package in node

Why node?

Node is a asynchronous program

In any server side programming like JSP, PHP, ASP, send task to server . wait until
complete the task then return content to the client . then ready to handle the next
request

In nodejs send the task to server. and immediately read to handle next request
Node js have default web server it run on 8080 port

Node Js Advantages
1. Efficient performance
2. Easier development process
3. Reusable code
4. Ability to handle multiple requests
5. Asynchronous programming increases the performance
6. NodeJs may be run on windows ,mac (or) Linux system
Node js process model :

1. The Traditional Web server:


The traditional web server model consists of a pool of threads which may process
requests . Each time a new request comes in , it is assigned to different thread in the
pool . in the event a request is received and a thread is not available , the request will
have to wait until a previous request will have to wait until a previous request finishes
, a response is returned to the thread pool in this way , the web server model is
synchronous or blocking thread

The Node.js Process model: -


The Node.js process model differs from traditional web servers in that Node.js runs in
a single process with requests being processed on a single thread. One advantage of
this is that Node.js requires far fewer resources. When a request comes in, it will be
placed in an event queue. Node.js uses an event loop to listen for events to be raised
for an asynchronous job. The event loop continuously runs, receiving requests from the
event queue.

There are two scenarios that will occur depending on the nature of the request. If the
request is non-blocking, it does not involve any long-running processes or data
requests, the response will be immediately prepared and then sent back to the client. In
the event the request is blocking, requiring I/O operations, the request will be sent to a
worker thread pool. The request will have an associated call-back function that will
fire when the request is finished and the worker thread can send the request to the
event loop to be sent back to the client. In this way, when the single thread receives a
blocking request, it hands it off so that the thread can process other requests in the
meantime. In this way Node.js is inherently asynchronous.
The combination of the asynchronous nature of Node.js plus the reduced resource
consumption of the single-threaded process leads to a significant increase in
performance. It should be noted, however, that Node.js does not excel with CPU-
intensive operations such as image processing and computationally-expensive work.

Node Module System


Node modules to be the same as javascript libraries
Nodejs has as set of built-in modules which you can use without any further installation
Require():-
Require function is used to include the modules in node js
In node three types of modules
1. Core Modules
2. Local Modules
3. Third party Modules

1. Core Modules:
Built-in modules we consider as core modules . it means pre-defined modules for example
filesystem modules like read,write,update,delete functions belongs to filesystem module
.These modules we called as built-in or pre-defined modules
Example :
require(‘fs’)
2. Local modules :
Local module are created locally in your node js it means user-defined module below
example is example of local module
Utility.js
let a ="ACET";

module.exports=a;

module.exports : The module.exports in Node.js is used to export any literal,


function or object as a module.
module.exports = literal | function | object

User.js
const a= require('./utility.js')
console.log(a);

3. Third party Module :


Third party module are modules are available online using the node package manager
(NPM)

Example: npm install express


Http Module in Node:
It’s a built in Node.js module that allows Node.js to transfer data over the Hyper Text Transfer
Protocol (HTTP). If you want to use it all that is needed is this code.
How to import http module in node :
Server.js
var http = require(“http”);
using require method to add http module in node
//create server in node
Create server using HTTP module:
var http = require(“http”);
http.Createserver(function(req,res)
{
res.write(“hello I am browser…”);
res.send()
}).listen(8080);
After written this code execute the code using terminal using below code
Node Js File server :
The Node.js File System module allows you to work with the file system on your computer
To include the file system module use the require() method
Common File system module:
 ReadFile()
 CreateFile()
 UpdateFile()
 DeleteFile()
 RenameFile
fs.Readfile()
method is used to read file on your computer

 CreateFile

For creating a file we have to depend on the 3 modules

fs.append():- appends specified content to file

fs.open():- used to open file with read/write permission

fs.writefile():- replace specified file and content if it exists


 UpdateFiles

fs.append() :- appends specified content to file


fs.writefile() :- replace specified file and content if it exists

 Delete Files

Fs.unlik():- delete specified file

NPM (Node Package Manager):


NPM is a package manager for node.js in node js we have built-in modules but when
we need external modules for more functionality then we have to install external
modules

https://www.npmjs.com/ is official website for node package manager for external


modules for more functionality

after visit this web search module based on our requirement like below image

How to install external modules using npm


>npm install express
>npm install socket.io
Express JS:
Express.js is a web framework for Node.js. It is a fast, robust and asynchronous in nature.

Express.js is a web application framework for Node.js. It provides various features that make
web application development fast and easy which otherwise takes more time using only
Node.js.

Express.js is based on the Node.js middleware module called connect which in turn
uses http module. So, any middleware which is based on connect will also work with
Express.js
Advantages of Express Js:

1. Makes Node.js web application development fast and easy.


2. Easy to configure and customize.
3. Allows you to define routes of your application based on HTTP methods and URLs.
4. Allows you to create REST API server.
5. Easy to connect with databases such as MongoDB, Redis, MySQL

Why Use Express:

1.Fast I/O

2.Asynchronous and single threaded

3.MVC like Structure

4.Robust API Makes routing easy

Installation of Express js:

Express js is a frame work for web development in Node

PS E:\NODEJS\express>Node install express

Through above command we complete the installation of the express

After installation of express we can find the {} package-lock.json in visual studio


Let’s Hello with expressJs

const exp = require('express');


const app = exp()
app.get('',(req,res)=>{
res.send('Hello express!')
})

app.listen(8000,()=>{
console.log('running on port 8000.')
})

In above we get and listen method get method is process the request and response on the
particular url

Listen is use to run the server based on specified port

ExpressJs Routing:

Routing refers to 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).
Each route can have one or more handler functions, which are executed when the route is
matched.

Route definition takes following structure :


App.method(path, handler )
Path: is path on the server
Handler : is the function executed when the router is matched (call back function)
Routing methods:
express = require(“express”);
app = express();
//above two statements used to import the express and create object for app
app.get() => respond with hello world on the home page
example: app.get(‘/’,(res,req)=>{res.send(“hello from get”)});
app.post() => respond to post request on the root route (‘/’) . the applications home page.
example: app.post(‘/’,(req,res) =>{res.send(“hello from post”)});
app.put()=> respond to put request to the user
example: app.put(‘/path’,(req,res) =>{res.send(“hello from put”)});
app.delete() => Respond to delete request to the user / route:
example :app.delete(‘/path’,(req,res)=>{res.send(“go to delete request at /user”)});
app.all()=> all function is just like the router method to processing respond request
example: app.all('/', (req, res) => {
res.send("all Request Called")
})

Dynamic routing in express:

const exp = require('express');


const app = exp()
app.get('',(req,res)=>{
res.send('Hello express!')
})
app.post('/ACET',(req,res)=>{

res.send('Aditya College Of Engineering & Technology')


})
app.listen(8000,()=>{
console.log('running on port 8000.')
})

Above code we can go through 2 urls


1. https://localhost:8000/
above url we get
Hello express
2. https://localhost:8000/ACET
through above url we get
Aditya college of engineering and technology
MVC in Express Js
MVC stands for Model, View, Controller is an architectural pattern that separates an
application into three main logical components: the model, the view, and the controller. Each
one of these components is built to handle specific development aspects of an application.

MVC is architecture used in building Web Servers that focus on reliability and making the
development process much simpler and easier since it composes the Web Server into three
separate parts.

 Controller is the part that takes care of client request processing which handles
the HTTP Request and returns a response the response could be either a JSON if
you’re calling an API endpoint or regular HTML webpage.

 Model is the database interface which lets you interact with the database API and
create different entity schemas of your app on the database (MySQL, MongoDB),
it gets called from controller depending on the client’s request if it needs a stored
data then the controller will ask the model interface for providing it with the
needed data.

 View is what compiles and renders into plain HTML and what the client in most
cases going to get back as a response of what he requested (for ex: to view his
profile details), the view needs to use a Template Engine for doing the rendering
process where the controller feed it with needed data (data from database and
client) and the view renders and convert everything into plain HTML that the
browser could understand and display.
Middleware:

Express.js is a routing and Middleware framework for handling the different routing of the
webpage and it works between the request and response cycle. Middleware gets executed
after the server receives the request and before the controller actions send the response.
Middleware has the access to the request object, responses object, and next, it can process
the request before the server send a response. An Express-based application is a series of
middleware function calls.

Advantages of using middleware:


 Middleware can process request objects multiple times before the server works
for that request.
 Middleware can be used to add logging and authentication functionality.
 Middleware improves client-side rendering performance.
 Middleware is used for setting some specific HTTP headers.
 Middleware helps for Optimization and better performance.

Middleware Chaining: Middleware can be chained from one to another, Hence creating a
chain of functions that are executed in order. The last function sends the response back to
the browser. So, before sending the response back to the browser the different middleware
process the request.

The next() function in the express is responsible for calling the next middleware function if
there is one.

Modified requests will be available to each middleware via the next function –
In the above case, the incoming request is modified and various operations are performed
using several middlewares, and middleware is chained using the next function. The router
sends the response back to the browser.
Middleware Syntax: The basic syntax for the middleware functions are as follows –
app.get(path, (req, res, next) => {}, (req, res) => {})

The middle part (req,res,next)=>{} is the middleware function. Here we generally perform
the actions required before the user is allowed to view the webpage or call the data and
many other functions. So let us create our own middleware and see its uses.

Step 1: Go to your project directory and enter the following command to create a NodeJs
project. Make sure that NodeJs is installed in your machine.
npm init -y
It will create a package.json file.

Step 2: Install two dependencies using the following command.


npm install express nodemon

Step 3: In the scripts section of the package.json file, add the following code line.
"start": "nodemon index.js",
Step 4: Create an index.js file in the directory. Make sure that it is not inside any
subdirectories of the directory you are working in.
Project Structure: It will look like the following.

Template Engine in express js:

A template engine facilitates you to use static template files in your applications. At runtime,
it replaces variables in a template file with actual values, and transforms the template into an
HTML file sent to the client. So this approach is preferred to design HTML pages easily.

Following is a list of some popular template engines that work with Express.js:

o Pug (formerly known as jade)


o mustache
o dust
o atpl
o eco
o ect
o ejs

pug is most used template in express js

let see how to implement pug file and how to include pug in js file

installation of pug

>>npm install pug –-save

Now pug is installed in our node environment .

now we create pug file . name as index.pug

html
head
title= title
body
h1= message

above file sample file of the pug name index.pug

now we have to implement expressjs file to use above template(index.pug) . for use this template
we need to set view engine for template( pug file) for that we need to use app.set() method below
code is example to how to use the template using pug in express js

var express = require('express');


var app = express();
//set view engine
app.set("view engine","pug")

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

res.render('index', { title: 'Hey', message: 'Hello there!' })

})

Observe above code we pass the values in attributes of index pug file
Error Handling :

Error handling in Express is done using middleware. But this middleware has special
properties. The error handling middleware are defined in the same way as other middleware
functions, except that error-handling functions MUST have four arguments instead of three
– err, req, res, next. For example, to send a response on any error, we can use

app.use(function(err, req, res, next) {


console.error(err.stack);
res.status(500).send('Not working ');
});
Till now we were handling errors in the routes itself. The error handling middleware allows us
to separate our error logic and send responses accordingly. The next() method we discussed in
middleware takes us to next middleware/route handler.
For error handling, we have the next(err) function. A call to this function skips all middleware
and matches us to the next error handler for that route. Let us understand this through an
example.
var express = require('express');
var app = express();
app.get('/', function(req, res){
//Create an error and pass it to the next function
var err = new Error("Something went wrong");
next(err);
});
/* other route handlers and middleware here
*/
//An error handling middleware
app.use(function(err, req, res, next) {
res.status(500);
res.send("Oops, Not Working .")
});
app.listen(3000);

based on above code

error message display on browser like below :


Debugging in express Js

In express, there is a module present called DEBUG that gives log information. It tells
about middleware functions, application mode, their status, and also about the requests and
responses made to the server.
To use this module while running the express app, set the DEBUG environment variable to
express:*
For widows use the corresponding command :

set DEBUG=express:* & node index.js

For Other Operating Systems:

$ DEBUG=express:* node index.js

Running this command on the default app generated by the express generator prints the
following output:

$ DEBUG=express:* node ./bin/www


express:router:route new / +0ms
express:router:layer new / +1ms
express:router:route get / +1ms
express:router:layer new / +0ms
express:router:route new / +1ms
express:router:layer new / +0ms
express:router:route get / +0ms
express:router:layer new / +0ms
express:application compile etag weak +1ms
express:application compile query parser extended +0ms
express:application compile trust proxy false +0ms
express:application booting in development mode +1ms

When running through Node.js, you can set a few environment variables that will change the
behaviour of the debug logging:
Name Purpose
DEBUG Enables /disables specific debugging name
spaces .
DEBUG_COLORS Whether or not use colors in debug output
DEBUG_DEPTH Object inspection depth
DEBUG_FD
File description to write debug output to

DEBUG_SHOW_HIDDEN
Shows hidden properties on inspected
objects

API HANDLING IN EXPRESSJS


Restful API is very popular and commonly used to create APIs for web-based
applications. Express is a back-end web application framework of node js, and with the help
of express, we can create an API very easily. This tutorial on Express REST API will walk
you through all the topics on Express REST API.

REST API is the standard way to send and receive data for web services.

A client sends a req which first goes to the rest API and then to the database to get or put the
data after that, it will again go to the rest API and then to the client. Using an API is just like
using a website in a browser, but instead of clicking on buttons, we write code to req data
from the server. It's incredibly adaptable and can handle multiple types of requests

What Is REST API?

REST (Representational state transfer) is a popular architecture that is used to create web
services.

API (Application Programming Interface is a code that allows two software programs to
communicate with each other.

REST API is a software that allows two apps to communicate with one another over the
internet and through numerous devices.
HTTP Request Types?

HTTP Requests are simply messages that are sent by the client to do some tasks on the server

 GET - Get command is used to request data from the server, but mainly this
method is used to read data

 PATCH - This command is used to update, change or replace the data

 POST - The post method is used to create new or to edit already existing data

 Delete - This delete command is used to delete the data completely from the server

API Using Express and Its Architecture?

A request is sent by the client in the form of a JSON file, and with the help of an HTTP
request which gets a patch post and delete, it will go to the server first then, the server sends
back the response to the client in the form of a message to tell what happened to your request.

For crate the JSON File we need to type below command

E:\NODEJS\express> npm init -y

After installation init pakage.josn like below figure


Above screen short is help to understand json file will create after installation
npm init -y
Deployment in NodeJS

Once your site is finished (or finished "enough" to start public testing) you're going to need to
host it somewhere more public and accessible than your personal development computer.

Up to now, you've been working in a development environment, using Express/Node as a


web server to share your site to the local browser/network, and running your website with
(insecure) development settings that expose debugging and other private information. Before
you can host a website externally, you're first going to have to:

 Choose an environment for hosting the Express app.


 Make a few changes to your project settings.
 Set up a production-level infrastructure for serving your website.

Let’s see what steps we need to Deployment the node.js application

STEP 1: Create a “package.json” file using the following command

>> npm init

STEP 2: Create a file called “app.js” inside your project folder


STEP 3: Create a html file “head.html”
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>This is the Homepage</h1>
<p><a href="/tailPage">Go to Next Page</a></p>
</body>
STEP 4: Create another html file “tail.html”
Content of tail.html is
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>WORKING</h1>
</body>

STEP 5: Open “app.js” file created in step 2 and copy paste the following code in it
var http = require('http');
var fs = require('fs'); // to get data from html file

http.createServer(function (req, res) {


res.writeHead(200, { 'Content-Type': 'text/html' });
var url = req.url;
if (url === "/") {
fs.readFile("head.html", function (err, pgres) {
if (err)
res.write("HEAD.HTML NOT FOUND");
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(pgres);
res.end();
}
});
}
else if (url === "/tailPage") {
fs.readFile("tail.html", function (err, pgres) {
if (err)
res.write("TAIL.HTML NOT FOUND");
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(pgres);
res.end();
}
});
}

}).listen(3000, function () {
console.log("SERVER STARTED PORT: 3000");
});
STEP 6: Open the terminal again and write the following command to run the server

node app.js
We have successfully created the sample application, we are now going to deploy it on the
web.
There’s are many cloud platforms like AWS, Heroku, Digital Ocean, etc.

You might also like