SlideShare a Scribd company logo
Node.js web-based Example
Node.js
•Node.js is an open source server environment.
•Node.js allows you to run JavaScript on the
server.
•Node.js runs on various platforms (Windows,
Linux, Unix, Mac OS X, etc.)
Run a local server in order to
start using node.js in the
browser and do server side tasks
Getting Started
• Create a Node.js file named “Example.js", and add the following code:
• Create a Node.js file named “Example.js",
Example.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
node Example.js
Start your internet browser, and type in the address:
http://localhost:8080
var util = require("util");
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Kongu IT World!');
}).listen(8080);
util.log("Server running at https://localhost:8080/");
Server.js
var http = require('http');
var fs=require('fs');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var myreadSt=fs.createReadStream('Sample.html');
myreadSt.pipe(res);
}).listen(8087);
Sample.html
<!DOCTYPE html>
<html>
<body>
<h1 style="color:blue;">A Blue
Heading</h1>
<p style="color:red;">A red
paragraph.</p>
</body>
</html>
Node.js fs.createReadStream() Method
• createReadStream() method is an inbuilt application programming
interface of fs module which allow you to open up a
file/stream and read the data present in it.
Syntax:
fs.createReadStream( path, options )
path: This parameter holds the path of the file where to read the file.
It can be string, buffer or URL.
options: It is an optional parameter that holds string or object.
// Node.js program to demonstrate the
// fs.createReadStream() method
// Include fs module
let fs = require('fs'),
// Use fs.createReadStream() method
// to read the file
reader = fs.createReadStream('input.txt');
// Read and display the file data on console
reader.on('data', function (chunk) {
console.log(chunk.toString());
});
How to show the data in the
console.log() ? (node.js)
• The data is a transfer from server to client for a particular request in the form of a stream.
• The stream contains chunks.
• A chunk is a fragment of the data that is sent by the client to server all chunks concepts to
each other to make a buffer of the stream then the buffer is converted into meaningful
data
Syntax:
request.on('eventName',callback)
• Parameters: This function accepts the following two parameters:
• eventName: It is the name of the event that fired
• callback: It is the Callback function i.e Event handler of the particular event.
• Return type: The return type of this method is void.
What is chunk in Node.js ?
Index.html / Client side
<html>
<head>
<title></title>
</head>
<body>
<form action="http://localhost:8087">
Enter n1:<input type="text" name="n1" value=""/><br>
Enter n2:<input type="text" name="n2" value=""/><br>
<input type="submit" value="Login"/>
</form>
</body>
</html>
http=require('http');
url=require('url');
querystring = require('querystring’);
function onRequest(req,res){
var path = url.parse(req.url).pathname;
var query =url.parse(req.url).query;
var no1 =querystring.parse(query)["n1"];
var no2=querystring.parse(query)["n2"];
var sum=parseInt(no1)+parseInt(no2);
console.log(sum);
res.write("The result is "+" " + sum);
res.end();
}
http.createServer(onRequest).listen(4001);
console.log('Server has Started.......');
Server.js/ Server
side
Node.js URL Module
• The URL module splits up a web address into readable parts.
• Parse an address with the url.parse() method, and it will return a URL
object with each part of the address as properties:
Node.js Query String Module
• The Query String module provides a way of parsing the URL query
string.
• Query String Methods
Method Description
escape() Returns an escaped querystring
parse() Parses the querystring and returns an object
stringify() Stringifies an object, and returns a query string
unescape() Returns an unescaped query string
Node.js web-based Example
• A node.js web application contains the following three parts:
1. Import required modules: The "require" directive is used to load a
Node.js module.
2. Create server: You have to establish a server which will listen to
client's request similar to Apache HTTP Server.
3. Read request and return response: Server created in the second
step will read HTTP request made by client which can be a browser
or console and return the response.
How to create node.js web applications
• Import required module: The first step is to use ?require? directive
to load http module and store returned HTTP instance into http
variable.
For example:
var http = require("http");
Create server:
• In the second step, you have to use created http instance and
• call http.createServer() method to create server instance and
• then bind it at port 8081 using listen method associated with server
instance.
• Pass it a function with request and response parameters and write
the sample implementation to return "Hello World".
Combine step1 and step2 together in a file
named "main.js".
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 Worldn');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
File: main.js
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 Worldn');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
node main.js Now server is started.
Make a request to Node.js server:
Open http://127.0.0.1:8081/ in any browser. You will see the following result.
Node.js File System (FS)
• Node File System (fs) module can be imported using following syntax:
Syntax:
var fs = require("fs")
The createReadStream() method is an inbuilt application programming interface of
fs module which allow you to open up a file/stream and read the data present in it.
Syntax:
fs.createReadStream( path, options )
path: This parameter holds the path of the file where to read the file. It can be
string, buffer or URL.
options: It is an optional parameter that holds string or object.
// Node.js program to demonstrate the
// fs.createReadStream() method
// Include fs module
let fs = require('fs'),
// Use fs.createReadStream() method
// to read the file
reader = fs.createReadStream('input.txt');
// Read and display the file data on console
reader.on('data', function (chunk) {
console.log(chunk.toString());
});
With html file
const http = require('http')
const fs = require('fs')
const server = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/html' })
fs.createReadStream('index.html').pipe(res)
})
server.listen(process.env.PORT || 3000)
let http = require('http');
let fs = require('fs');
let handleRequest = (request, response) => {
fs.readFile('./index.html', null, function (error, data) {
if (error) {
response.writeHead(404);
respone.write('Whoops! File not found!');
} else {
response.write(data);
}
response.end();
});
};
http.createServer(handleRequest).listen(8000);

More Related Content

Similar to Node.js web-based Example :Run a local server in order to start using node.js in the browser and do server side tasks (20)

nodejs_at_a_glance, understanding java script
nodejs_at_a_glance, understanding java scriptnodejs_at_a_glance, understanding java script
nodejs_at_a_glance, understanding java script
mohammedarshadhussai4
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
Tom Croucher
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
Felix Geisendörfer
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
Felix Geisendörfer
 
A slightly advanced introduction to node.js
A slightly advanced introduction to node.jsA slightly advanced introduction to node.js
A slightly advanced introduction to node.js
Sudar Muthu
 
Nodejs
NodejsNodejs
Nodejs
Vinod Kumar Marupu
 
Node_basics.pptx
Node_basics.pptxNode_basics.pptx
Node_basics.pptx
Kongu Engineering College, Perundurai, Erode
 
node js.pptx
node js.pptxnode js.pptx
node js.pptx
PSK Technolgies Pvt. Ltd. IT Company Nagpur
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
Derek Anderson
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
Node.js - The New, New Hotness
Node.js - The New, New HotnessNode.js - The New, New Hotness
Node.js - The New, New Hotness
Daniel Shaw
 
About Node.js
About Node.jsAbout Node.js
About Node.js
Artemisa Yescas Engler
 
Node intro
Node introNode intro
Node intro
cloudhead
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Winston Hsieh
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
Node36
Node36Node36
Node36
beshoy semsem
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
Mike Brevoort
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Somkiat Puisungnoen
 

More from Kongu Engineering College, Perundurai, Erode (20)

Introduction to Generative AI refers to a subset of artificial intelligence
Introduction to Generative AI refers to a subset of artificial intelligenceIntroduction to Generative AI refers to a subset of artificial intelligence
Introduction to Generative AI refers to a subset of artificial intelligence
Kongu Engineering College, Perundurai, Erode
 
Introduction to Microsoft Power BI is a business analytics service
Introduction to Microsoft Power BI is a business analytics serviceIntroduction to Microsoft Power BI is a business analytics service
Introduction to Microsoft Power BI is a business analytics service
Kongu Engineering College, Perundurai, Erode
 
Connect to NoSQL Database (MongoDB) using Node JS & Connect Node.js with NoSQ...
Connect to NoSQL Database (MongoDB) using Node JS & Connect Node.js with NoSQ...Connect to NoSQL Database (MongoDB) using Node JS & Connect Node.js with NoSQ...
Connect to NoSQL Database (MongoDB) using Node JS & Connect Node.js with NoSQ...
Kongu Engineering College, Perundurai, Erode
 
concept of server-side JavaScript / JS Framework: NODEJS
concept of server-side JavaScript / JS Framework: NODEJSconcept of server-side JavaScript / JS Framework: NODEJS
concept of server-side JavaScript / JS Framework: NODEJS
Kongu Engineering College, Perundurai, Erode
 
Concepts of Satellite Communication and types and its applications
Concepts of Satellite Communication  and types and its applicationsConcepts of Satellite Communication  and types and its applications
Concepts of Satellite Communication and types and its applications
Kongu Engineering College, Perundurai, Erode
 
Concepts of Mobile Communication Wireless LANs, Bluetooth , HiperLAN
Concepts of Mobile Communication Wireless LANs, Bluetooth , HiperLANConcepts of Mobile Communication Wireless LANs, Bluetooth , HiperLAN
Concepts of Mobile Communication Wireless LANs, Bluetooth , HiperLAN
Kongu Engineering College, Perundurai, Erode
 
Web Technology Introduction framework.pptx
Web Technology Introduction framework.pptxWeb Technology Introduction framework.pptx
Web Technology Introduction framework.pptx
Kongu Engineering College, Perundurai, Erode
 
Computer Network - Unicast Routing Distance vector Link state vector
Computer Network - Unicast Routing Distance vector Link state vectorComputer Network - Unicast Routing Distance vector Link state vector
Computer Network - Unicast Routing Distance vector Link state vector
Kongu Engineering College, Perundurai, Erode
 
Android SQLite database oriented application development
Android SQLite database oriented application developmentAndroid SQLite database oriented application development
Android SQLite database oriented application development
Kongu Engineering College, Perundurai, Erode
 
Android Application Development Programming
Android Application Development ProgrammingAndroid Application Development Programming
Android Application Development Programming
Kongu Engineering College, Perundurai, Erode
 
Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
Kongu Engineering College, Perundurai, Erode
 
A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...
Kongu Engineering College, Perundurai, Erode
 
SOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptxSOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptx
Kongu Engineering College, Perundurai, Erode
 
Application Layer.pptx
Application Layer.pptxApplication Layer.pptx
Application Layer.pptx
Kongu Engineering College, Perundurai, Erode
 
Connect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptxConnect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptx
Kongu Engineering College, Perundurai, Erode
 
Navigation Bar.pptx
Navigation Bar.pptxNavigation Bar.pptx
Navigation Bar.pptx
Kongu Engineering College, Perundurai, Erode
 
Bootstarp installation.pptx
Bootstarp installation.pptxBootstarp installation.pptx
Bootstarp installation.pptx
Kongu Engineering College, Perundurai, Erode
 
nested_Object as Parameter & Recursion_Later_commamd.pptx
nested_Object as Parameter  & Recursion_Later_commamd.pptxnested_Object as Parameter  & Recursion_Later_commamd.pptx
nested_Object as Parameter & Recursion_Later_commamd.pptx
Kongu Engineering College, Perundurai, Erode
 
Chapter 3.pdf
Chapter 3.pdfChapter 3.pdf
Chapter 3.pdf
Kongu Engineering College, Perundurai, Erode
 
Introduction to Social Media and Social Networks.pdf
Introduction to Social Media and Social Networks.pdfIntroduction to Social Media and Social Networks.pdf
Introduction to Social Media and Social Networks.pdf
Kongu Engineering College, Perundurai, Erode
 
Ad

Recently uploaded (20)

Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Ben Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding WorldBen Blair - Operating Safely in a Vibe Coding World
Ben Blair - Operating Safely in a Vibe Coding World
AWS Chicago
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Ad

Node.js web-based Example :Run a local server in order to start using node.js in the browser and do server side tasks

  • 2. Node.js •Node.js is an open source server environment. •Node.js allows you to run JavaScript on the server. •Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • 3. Run a local server in order to start using node.js in the browser and do server side tasks
  • 4. Getting Started • Create a Node.js file named “Example.js", and add the following code: • Create a Node.js file named “Example.js", Example.js var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Hello World!'); }).listen(8080); node Example.js Start your internet browser, and type in the address: http://localhost:8080
  • 5. var util = require("util"); var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Kongu IT World!'); }).listen(8080); util.log("Server running at https://localhost:8080/");
  • 6. Server.js var http = require('http'); var fs=require('fs'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); var myreadSt=fs.createReadStream('Sample.html'); myreadSt.pipe(res); }).listen(8087); Sample.html <!DOCTYPE html> <html> <body> <h1 style="color:blue;">A Blue Heading</h1> <p style="color:red;">A red paragraph.</p> </body> </html>
  • 7. Node.js fs.createReadStream() Method • createReadStream() method is an inbuilt application programming interface of fs module which allow you to open up a file/stream and read the data present in it. Syntax: fs.createReadStream( path, options ) path: This parameter holds the path of the file where to read the file. It can be string, buffer or URL. options: It is an optional parameter that holds string or object.
  • 8. // Node.js program to demonstrate the // fs.createReadStream() method // Include fs module let fs = require('fs'), // Use fs.createReadStream() method // to read the file reader = fs.createReadStream('input.txt'); // Read and display the file data on console reader.on('data', function (chunk) { console.log(chunk.toString()); }); How to show the data in the console.log() ? (node.js)
  • 9. • The data is a transfer from server to client for a particular request in the form of a stream. • The stream contains chunks. • A chunk is a fragment of the data that is sent by the client to server all chunks concepts to each other to make a buffer of the stream then the buffer is converted into meaningful data Syntax: request.on('eventName',callback) • Parameters: This function accepts the following two parameters: • eventName: It is the name of the event that fired • callback: It is the Callback function i.e Event handler of the particular event. • Return type: The return type of this method is void. What is chunk in Node.js ?
  • 10. Index.html / Client side <html> <head> <title></title> </head> <body> <form action="http://localhost:8087"> Enter n1:<input type="text" name="n1" value=""/><br> Enter n2:<input type="text" name="n2" value=""/><br> <input type="submit" value="Login"/> </form> </body> </html>
  • 11. http=require('http'); url=require('url'); querystring = require('querystring’); function onRequest(req,res){ var path = url.parse(req.url).pathname; var query =url.parse(req.url).query; var no1 =querystring.parse(query)["n1"]; var no2=querystring.parse(query)["n2"]; var sum=parseInt(no1)+parseInt(no2); console.log(sum); res.write("The result is "+" " + sum); res.end(); } http.createServer(onRequest).listen(4001); console.log('Server has Started.......'); Server.js/ Server side
  • 12. Node.js URL Module • The URL module splits up a web address into readable parts. • Parse an address with the url.parse() method, and it will return a URL object with each part of the address as properties:
  • 13. Node.js Query String Module • The Query String module provides a way of parsing the URL query string. • Query String Methods Method Description escape() Returns an escaped querystring parse() Parses the querystring and returns an object stringify() Stringifies an object, and returns a query string unescape() Returns an unescaped query string
  • 14. Node.js web-based Example • A node.js web application contains the following three parts: 1. Import required modules: The "require" directive is used to load a Node.js module. 2. Create server: You have to establish a server which will listen to client's request similar to Apache HTTP Server. 3. Read request and return response: Server created in the second step will read HTTP request made by client which can be a browser or console and return the response.
  • 15. How to create node.js web applications • Import required module: The first step is to use ?require? directive to load http module and store returned HTTP instance into http variable. For example: var http = require("http");
  • 16. Create server: • In the second step, you have to use created http instance and • call http.createServer() method to create server instance and • then bind it at port 8081 using listen method associated with server instance. • Pass it a function with request and response parameters and write the sample implementation to return "Hello World".
  • 17. Combine step1 and step2 together in a file named "main.js". 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 Worldn'); }).listen(8081); // Console will print the message console.log('Server running at http://127.0.0.1:8081/');
  • 18. File: main.js 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 Worldn'); }).listen(8081); // Console will print the message console.log('Server running at http://127.0.0.1:8081/');
  • 19. node main.js Now server is started.
  • 20. Make a request to Node.js server: Open http://127.0.0.1:8081/ in any browser. You will see the following result.
  • 21. Node.js File System (FS) • Node File System (fs) module can be imported using following syntax: Syntax: var fs = require("fs") The createReadStream() method is an inbuilt application programming interface of fs module which allow you to open up a file/stream and read the data present in it. Syntax: fs.createReadStream( path, options ) path: This parameter holds the path of the file where to read the file. It can be string, buffer or URL. options: It is an optional parameter that holds string or object.
  • 22. // Node.js program to demonstrate the // fs.createReadStream() method // Include fs module let fs = require('fs'), // Use fs.createReadStream() method // to read the file reader = fs.createReadStream('input.txt'); // Read and display the file data on console reader.on('data', function (chunk) { console.log(chunk.toString()); });
  • 23. With html file const http = require('http') const fs = require('fs') const server = http.createServer((req, res) => { res.writeHead(200, { 'content-type': 'text/html' }) fs.createReadStream('index.html').pipe(res) }) server.listen(process.env.PORT || 3000)
  • 24. let http = require('http'); let fs = require('fs'); let handleRequest = (request, response) => { fs.readFile('./index.html', null, function (error, data) { if (error) { response.writeHead(404); respone.write('Whoops! File not found!'); } else { response.write(data); } response.end(); }); }; http.createServer(handleRequest).listen(8000);