0% found this document useful (0 votes)
5 views51 pages

NodeJS

The document provides an overview of web servers, their architecture, and how they handle client requests. It discusses Node.js, its components, and how to create a basic server application, as well as the Express framework for building web applications. Additionally, it covers database operations using MySQL in Node.js, including creating databases and tables, inserting records, and retrieving data.

Uploaded by

vaalinandhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views51 pages

NodeJS

The document provides an overview of web servers, their architecture, and how they handle client requests. It discusses Node.js, its components, and how to create a basic server application, as well as the Express framework for building web applications. Additionally, it covers database operations using MySQL in Node.js, including creating databases and tables, inserting records, and retrieving data.

Uploaded by

vaalinandhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Web server

• Web server is a computer where the web


content is stored.
• Basically web server is used to host the web sites
but there exists other web servers also such as
gaming, storage, FTP, email etc.
• Web server respond to the client request in
either of the following two ways:
• Sending the file to the client associated with the
requested URL.
• Generating response by invoking a script and
communicating with database.
Web Server Working
Architecture

• Web Server Architecture follows the following


two approaches:
• Concurrent Approach
• Concurrent approach allows the web server to
handle multiple client requests at the same
time. It can be achieved by following methods:
• Multi-process
• Multi-threaded
• Hybrid method.
Architecture

Multi-processing
• In this a single process (parent process) initiates several single-
threaded child processes and distribute incoming requests to
these child processes. Each of the child processes are
responsible for handling single request.
• It is the responsibility of parent process to monitor the load and
decide if processes should be killed or forked.
Multi-threaded
• Unlike Multi-process, it creates multiple single-threaded process.
Hybrid
• It is combination of above two approaches. In this approach
multiple process are created and each process initiates multiple
threads. Each of the threads handles one connection. Using
multiple threads in single process results in less load on system
resource
Examples

S.N. Web Server Descriptino


1 Apache HTTP Server
This is the most popular web server in the world developed by the Apache
Software Foundation.

2. Internet Information Services (IIS)


The Internet Information Server (IIS) is a high performance Web Server from
Microsoft.

3. Lighttpd
The lighttpd, pronounced lighty is also a free web server that is distributed
with the FreeBSD operating system.

4. Sun Java System Web Server


This web server from Sun Microsystems is suited for medium and large web
sites.
5. Jigsaw Server
Jigsaw (W3C's Server) comes from the World Wide Web Consortium. It is open
source and free and can run on various platforms like Linux, UNIX, Windows,
and Mac OS X Free BSD etc.
Node.js
• Node.js is a very powerful JavaScript-based
platform built on Google Chrome's JavaScript
V8 Engine.
• It is used to develop I/O intensive web
applications like video streaming sites, single-
page applications, and other web applications.
• Node.js is open source, completely free, and
used by thousands of developers around the
world.
Node.js components
• Node.js application consists of the following
three components
• Import required modules − We use
the require directive to load Node.js modules.
• Create server − A server which will listen to
client's requests similar to Apache HTTP Server.
• Read request and return response − The server
created in an earlier step will read the HTTP
request made by the client which can be a
browser or a console and return the response.
Creating Node.js Application

• Step 1 - Import Required Module


• We use the require directive to load the http
module and store the returned HTTP instance
into an http variable as follows −
var http = require("http");
Step 2 - Create Server

• We use the created http instance and call http.createServer() method


to create a server instance and then we bind it at port 8081 using
the listen method associated with the server instance. Pass it a function
with parameters request and response. Write the sample
implementation to always return "Hello World".
• http.createServer(function (request, response) {
• // Send the HTTP header
• // HTTP Status: 200 : OK
• // Content Type: text/plain
• response.writeHead(200, {'Content-Type': 'text/plain'});
• // Send the response body as "Hello World" response. end('Hello
World\n'); }).
• listen(8081);
• // Console will print the message
• console.log('Server running at http://127.0.0.1:8081/');
Step 3 - Testing Request & Response

• Let's put step 1 and 2 together in a file called main.js and start
our HTTP server as shown below −
• var http = require("http");
• http.createServer(function (request, response) {
• // Send the HTTP header //
• HTTP Status: 200 : OK //
• Content Type: text/plain response.writeHead(200, {'Content-
Type': 'text/plain'});
• // Send the response body as "Hello World" response.end('Hello
World\n'); }).
• listen(8081);
• // Console will print the message console.log('Server running at
http://127.0.0.1:8081/');
Execution
• Now execute the main.js to start the server as
follows −
• $ node main.js
• Verify the Output. Server has started.
• Server running at http://127.0.0.1:8081/
Make a Request to the Node.js Server

• Open http://127.0.0.1:8081/ in any browser


and observe the following result.
NPM
• Node Package Manager (NPM) provides two
main functionalities −
• Online repositories for node.js
packages/modules which are searchable on
search.nodejs.org
• Command line utility to install Node.js
packages, do version management and
dependency management of Node.js
packages.
Node.js HTTP Module

• Node.js has a built-in module called HTTP,


which allows Node.js to transfer data over the
Hyper Text Transfer Protocol (HTTP).
• To include the HTTP module, use
the require() method:
var http = require('http');
• The HTTP module can create an HTTP server
that listens to server ports and gives a response
back to the client.
• Use the createServer() method to create an
HTTP server
HTTP Module
Create server
• var http = require('http');
//create a server object:
http.createServer(function (req, res)
{
res.write('Hello World!'); //write a response
to the client
res.end(); //end the response
}).listen(8080);
//the server object listens on port 8080
Read the Query String

• he function passed into the http.createServer() has


a req argument that represents the request from the
client, as an object (http.IncomingMessage object).
• This object has a property called "url" which holds
the part of the url that comes after the domain name:
• demo_http_url.js
• var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(req.url);
res.end();
}).listen(8080);
Node.js - Express Framework

• 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 on HTTP Method and URL.
• Allows to dynamically render HTML Pages based on
passing arguments to templates.
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) })
OUTPUT
• 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,
Template engines

• Pug: Haml-inspired template engine (formerly Jade).


• Haml.js: Haml implementation.
• EJS: Embedded JavaScript template engine.
• hbs: Adapter for Handlebars.js, an extension of Mustache.js template
engine.
• Squirrelly: Blazing-fast template engine that supports partials, helpers,
custom tags, filters, and caching. Not white-space sensitive, works with
any language.
• Eta: Super-fast lightweight embedded JS template engine. Supports
custom delimiters, async, whitespace control, partials, caching, plugins.
• combyne.js: A template engine that hopefully works the way you’d
expect.
• Nunjucks: Inspired by jinja/twig.
• marko: A fast and lightweight HTML-based templating engine that
compiles templates to CommonJS modules and supports streaming, async
rendering and custom tags. (Renders directly to the HTTP response
stream).
• whiskers: Small, fast, mustachioed.
Template engines

• Blade: HTML Template Compiler, inspired by Jade & Haml.


• Haml-Coffee: Haml templates where you can write inline CoffeeScript.
• express-hbs: Handlebars with layouts, partials and blocks for express 3 from
Barc.
• express-handlebars: A Handlebars view engine for Express which doesn’t suck.
• express-views-dom: A DOM view engine for Express.
• rivets-server: Render Rivets.js templates on the server.
• LiquidJS: A simple, expressive and safe template engine.
• express-tl: A template-literal engine implementation for Express.
• Twing: First-class Twig engine for Node.js.
• Sprightly: A very light-weight JS template engine (45 lines of code), that
consists of all the bare-bones features that you want to see in a template
engine.
• html-express-js: A small template engine for those that want to just serve static
or dynamic HTML pages using native JavaScript.
• The Consolidate.js library unifies the APIs of these template engines to a single
Express-compatible API.
ExpressJS - Serving static files

• Static files are files that clients download as they are


from the server. Create a new directory, public. Express,
by default does not allow you to serve static files.
• You need to enable it using the following built-in
middleware.
• app.use(express.static('public'));
Note − Express looks up the files relative to the static
directory, so the name of the static directory is not part
of the URL.
• Note that the root route is now set to your public dir, so
all static files you load will be considering public as root.
ExpressJS - Serving static files

• To test that this is working fine, add any image


file in your new public dir and change its name
to "testimage.jpg". In your views, create a new
view and include this file like −
• html
• head
• body h3 Testing static file serving:
• img(src = "/testimage.jpg", alt = "Testing Image
Async Await with promises in Node.js
• Modern javascript brings with it the async-await feature
which enables developers to write asynchronous code in a
way that looks and feels synchronous.
• This helps to remove many of the problems with nesting
that promises have, and as a bonus can make
asynchronous code much easier to read and write.
• To use async-await, we just need to create an async
function in which we will implement our try-catch block.
• In the try block, we will await our promise to be
completed. If it gets resolved we will get the result
otherwise an error will be thrown through the catch block.
• Await can only be used inside an async function or async
callback or async arrow function.
Express.js – express.json() function

• express.json() is a built-in middleware function in Express. This method


is used to parse the incoming requests with JSON payloads and is based
upon the bodyparser.
• This method returns the middleware that only parses JSON and only
looks at the requests where the content-type header matches the type
option.
• Syntax
• express.json([options])Parameters
• Following are the different options available with this method
• options
– inflate – This enables or disables the handling of the deflated or compressed
bodies. Default: true
– limit – This controls the maximum size of the request body.
– reviver – This option is passed to the JSON.parse method as the second
argument.
– strict – This enables or disables the accepting arrays or objects.
– type – This determines the media type for the middleware that will be parsed.
Node.js MySQL Create Database

• CREATE DATABASE statement is used to create


a database in MySQL.
• Create a js file named javatpoint.js having the
following data in DB example folder.
Example

• var mysql = require('mysql');


• var con = mysql.createConnection({
• host: "localhost",
• user: "root",
• password: "12345"
• });
• con.connect(function(err) {
• if (err) throw err;
• console.log("Connected!");
• con.query("CREATE DATABASE javatpoint", function (err, result) {
• if (err) throw err;
• console.log("Database created");
• });
• });
Out put
• Now open command terminal and run the
following command:
• Node javatpoint.js
Verification

• To verify if the database is created or not, use


the SHOW DATABASES command. Before this,
go to initial path by using mysql-p command.
Node.js MySQL Create Table
• CREATE TABLE command is used to create a
table in MySQL. You must make it sure that
you define the name of the database when
you create the connection.
• Example
• For creating a table named "employees".
• Create a js file named employees.js having the
following data in DBexample folder
Example
• var mysql = require('mysql');
• var con = mysql.createConnection({
• host: "localhost",
• user: "root",
• password: "12345",
• database: "javatpoint"
• });
• con.connect(function(err) {
• if (err) throw err;
• console.log("Connected!");
• var sql = "CREATE TABLE employees (id INT, name VARCHAR(255), age INT(3),
city VARCHAR(255))";
• con.query(sql, function (err, result) {
• if (err) throw err;
• console.log("Table created");
• });
• });
OUTPUT
• Now open command terminal and run the
following command:
• Node employees.js
Node.js MySQL Insert Records

• INSERT INTO statement is used to insert


records in MySQL.
• Example
• Insert Single Record:
• Insert records in "employees" table.
• Create a js file named "insert" in DBexample
folder and put the following data into it:
Example

• var mysql = require('mysql');


• var con = mysql.createConnection({
• host: "localhost",
• user: "root",
• password: "12345",
• database: "javatpoint"
• });
• con.connect(function(err) {
• if (err) throw err;
• console.log("Connected!");
• var sql = "INSERT INTO employees (id, name, age, city) VALUES ('1', '
Ajeet Kumar', '27', 'Allahabad')";
• con.query(sql, function (err, result) {
• if (err) throw err;
• console.log("1 record inserted");
• });
Node.js MySQL Select Records

• Retrieve all data from the table "employees".

• Create a js file named select.js having the


following data in DB example folder.
Example
• var mysql = require('mysql');
• var con = mysql.createConnection({
• host: "localhost",
• user: "root",
• password: "12345",
• database: "javatpoint"
• });
• con.connect(function(err) {
• if (err) throw err;
• con.query("SELECT * FROM employees", function (err, result) {
• if (err) throw err;
• console.log(result);
• });
• });
Node.js MySQL Delete Records

• The DELETE FROM command is used to delete


records from the table.
• Example
• Delete employee from the table employees
where city is Delhi.
• Create a js file named "delete" in DBexample
folder and put the following data into it:
Example
• var mysql = require('mysql');
• var con = mysql.createConnection({
• host: "localhost",
• user: "root",
• password: "12345",
• database: "javatpoint"
• });
• con.connect(function(err) {
• if (err) throw err;
• var sql = "DELETE FROM employees WHERE city = 'Delhi'";
• con.query(sql, function (err, result) {
• if (err) throw err;
• console.log("Number of records deleted: " + result.affectedRows);
• });
• });
Out Put

• Now open command terminal and run the


following command:
• Node delete.js
MERN Stack

• MERN Stack is a collection of powerful


technologies and robust, used to develop scalable
master web applications comprising backend,
front-end, and database components.
• It is JavaScript that is used for the faster and easier
development of full-stack web applications.
• MERN Stack is a technology that is a user-friendly
full-stack JavaScript framework for building
applications and dynamic websites.
MERN Stack
MERN Stack
• MERN Stack consists of four main components or
can say four main technologies:
• M stands for MongoDB ( Database ), mainly used
for preparing document database and is a NoSQL
(Non-Structured Query Language ) Database System
• E stands for Express, mainly used for developing
Node.js web framework
• R stands for React, mainly used for developing a
client-side JavaScript framework
• N stands for js, mainly used for developing the
premier JavaScript web server
Why should we choose MERN Stack for building Mobile and Web applications

• Cost-effective:All the four technologies that are mentioned above, MERN


(MongoDB, Express.js, React.js, and Node.js) are used in MERN Stack is
built on JavaScript that makes it cost-effective and within less cost
investment user will able to get the better results or output.
• SEO friendly:Here, SEO (Search Engine Optimization) friendly means that
Google, Yahoo and other search engines can search each page on the
website efficiently and easily, interpret and correlate the content
effectively with the searched text and easily index it in their database. As
whenever websites are created using MERN technologies, then it is always
SEO friendly.
• Better performance: performance refers to the faster response between
backend and front-end and database, which ultimately improves the
website speed and yields better performance, thus providing a smooth
user experience.
Why should we choose MERN Stack for building Mobile and Web
applications
• Improves Security: It mainly concerns the security of applications generated using
MERN; her web application security refers to various processes, methods or
technologies used for protecting web servers and various web applications, such as
APIs (Application user interface) from the attack by internet-based threats.
Generally, secured hosting providers can easily integrate applications created using
the MERN stack. For more or better security Mongo DB and Node.js security tools
are also used.
• Provide the fastest delivery: Web applications and mobile applications created by
using MERN Stack are built much faster, which also helps to provide faster delivery
to our clients.
• Provides faster Modifications: MERN stack technologies supports quick
modifications as per the client's request in the mobile and web applications.
• Open Source: All the four technologies that are involved in MERN are open-source.
This feature allows developers to get solutions to queries that may evolve from the
open portals during development. As a result, it will be ultimately beneficial for a
developer.
• Easy to switch between client and server: MERN is very simple and fast because it
is written in only one language. And also, it is very easy to switch between client
and server.
Architectural Structure of MERN Stack

• MERN has a 3-tier Architecture system mainly


consisting of 3 layers -
• Web as front-end tier
• Server as the middle tier
• Database as backend tier
Architectural Structure of MERN Stack
Architectural Structure of MERN Stack

• Web or front-end tier - The top tier of the MERN stack is mainly
handled by React.js. It is one of the most prominent used open-
source front-end JavaScript libraries used for building Web
applications.
• It is famous for creating dynamic client-side applications. React
will help you construct complex interfaces by using single
components.
• It also connects those complex interfaces to data available on the
backend server.
• React is used to create mobile applications (React Native) and
web applications.
• React allows the reusability of code and can easily support it,
which has many benefits and is much time saver.
• It permits users to create large web applications that can easily
change the data of the page even without reloading the page.
Architectural Structure of MERN Stack
• Server or middle-tier - It is just next level from the top layer and is mainly
handled by two components of the MERN stack, i.e., Express.js and Node.js.
• These two's components handle it simultaneously because Express.js
maintained the Server-side framework, running inside the Node.js server.
• Express.js is one of the widely used backend development JavaScript
Frameworks.
• It allows developers to spin up robust APIs (Application Programming
Interface) and web servers much easier and simpler.
• It also adds helpful functionalities to Node.js HTTP (HyperText Transfer
Protocol) objects. Whereas on the other hand, Node.js plays a very
important role in itself.
• It is an open-source server environment, and it is a cross-platform runtime
environment for executing JavaScript code outside a browser.
• Node.js continuously uses JavaScript; thus, it's ultimately helpful for a
computer user to quickly create any net service or any net or mobile
application.
Architectural Structure of MERN Stack
• Database as backend tier - It is one of the most important levels of the MERN
Stack and is mainly handled by MongoDB;
• the main role of a database is to store all the data related to your application, for
example - content, statistics, information, user profiles, comments and so on. It
mainly stores all the data for safety purposes.
• It maintains a proper record, which usually returns the data to the user whenever
required. It mainly stores the data in the database.
• It generates two or more replica files of the data so that whenever the system
fails, it can retrieve the exact information or data that the user wanted earlier. It
implies that MongoDB is not based on the table-like relational database structure.
• On the other hand, it provides an altogether different mechanism for the retrieval
and storage of data. Mongo DB is the most popular NoSQL (NoSQL or Non
Structured Query Language) database, an open-source document-oriented
database.
• The term 'NoSQL' typically means a non-relational database that does not require
a fixed schema or proper relational tables to store the necessary data in it.
• MongoDB stores the data in a different format other than the relational tables,
consisting of rows and columns.
MERN STACK
Advantages of MERN Stack
• There are a lot of advantages of MERN Stack, some of them
are mentioned below -
• For a smooth development of any web application or mobile
app, it supports MVC (Model View Controller) architecture;
the main purpose of this architecture is to separate the
presentation details with the business logic.
• It covers all the web development stages starting from front-
end development to backend development with JavaScript.
• It is an open-source framework mainly used to develop web-
based or mobile applications and is supported by the
community.
• It is very fast and efficient compared to MEAN Stack and
mostly suitable for small applications, whereas MEAN Stack
is suitable for developing large applications.

You might also like