Unit 3 1
Unit 3 1
Unit 3 1
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
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?
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 :
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.
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;
User.js
const a= require('./utility.js')
console.log(a);
CreateFile
Delete Files
after visit this web search module based on our requirement like below image
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.Fast I/O
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
ExpressJs Routing:
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.
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 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.
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:
let see how to implement pug file and how to include pug in js file
installation of pug
html
head
title= title
body
h1= message
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
})
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
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 :
Running this command on the default app generated by the express generator prints the
following output:
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
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
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
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
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.
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.
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
}).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.