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)

PPT
nodejs_at_a_glance, understanding java script
mohammedarshadhussai4
 
KEY
A language for the Internet: Why JavaScript and Node.js is right for Internet...
Tom Croucher
 
PDF
5.node js
Geunhyung Kim
 
PPTX
Node JS Core Module PowerPoint Presentation
rajeshkannan750222
 
ODP
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
KEY
A language for the Internet: Why JavaScript and Node.js is right for Internet...
Tom Croucher
 
KEY
Node.js
Ian Oxley
 
PPTX
Introduction to node.js
Adrien Guéret
 
PPTX
Node.js Workshop - Sela SDP 2015
Nir Noy
 
PPTX
Intro to Node
Aaron Stannard
 
PDF
Web Server.pdf
Bareen Shaikh
 
PDF
Introduction to Node.js
Somkiat Puisungnoen
 
PPTX
Node.js: The What, The How and The When
FITC
 
PDF
Introduction to Node JS1.pdf
Bareen Shaikh
 
PPTX
Introduction to Node.js
Vikash Singh
 
PDF
Web Server and how we can design app in C#
caohansnnuedu
 
PDF
08 ajax
Ynon Perek
 
ODP
An Overview of Node.js
Ayush Mishra
 
nodejs_at_a_glance, understanding java script
mohammedarshadhussai4
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
Tom Croucher
 
5.node js
Geunhyung Kim
 
Node JS Core Module PowerPoint Presentation
rajeshkannan750222
 
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
Tom Croucher
 
Node.js
Ian Oxley
 
Introduction to node.js
Adrien Guéret
 
Node.js Workshop - Sela SDP 2015
Nir Noy
 
Intro to Node
Aaron Stannard
 
Web Server.pdf
Bareen Shaikh
 
Introduction to Node.js
Somkiat Puisungnoen
 
Node.js: The What, The How and The When
FITC
 
Introduction to Node JS1.pdf
Bareen Shaikh
 
Introduction to Node.js
Vikash Singh
 
Web Server and how we can design app in C#
caohansnnuedu
 
08 ajax
Ynon Perek
 
An Overview of Node.js
Ayush Mishra
 

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

PPTX
Introduction to Generative AI refers to a subset of artificial intelligence
Kongu Engineering College, Perundurai, Erode
 
PPTX
Introduction to Microsoft Power BI is a business analytics service
Kongu Engineering College, Perundurai, Erode
 
PPTX
Connect to NoSQL Database (MongoDB) using Node JS & Connect Node.js with NoSQ...
Kongu Engineering College, Perundurai, Erode
 
PPTX
concept of server-side JavaScript / JS Framework: NODEJS
Kongu Engineering College, Perundurai, Erode
 
PPT
Concepts of Satellite Communication and types and its applications
Kongu Engineering College, Perundurai, Erode
 
PPT
Concepts of Mobile Communication Wireless LANs, Bluetooth , HiperLAN
Kongu Engineering College, Perundurai, Erode
 
PPTX
Web Technology Introduction framework.pptx
Kongu Engineering College, Perundurai, Erode
 
PPTX
Computer Network - Unicast Routing Distance vector Link state vector
Kongu Engineering College, Perundurai, Erode
 
PPT
Android SQLite database oriented application development
Kongu Engineering College, Perundurai, Erode
 
PPT
Android Application Development Programming
Kongu Engineering College, Perundurai, Erode
 
PPTX
Introduction to Spring & Spring BootFramework
Kongu Engineering College, Perundurai, Erode
 
PPTX
A REST API (also called a RESTful API or RESTful web API) is an application p...
Kongu Engineering College, Perundurai, Erode
 
PPTX
SOA and Monolith Architecture - Micro Services.pptx
Kongu Engineering College, Perundurai, Erode
 
PPTX
Connect to NoSQL Database using Node JS.pptx
Kongu Engineering College, Perundurai, Erode
 
PPTX
Bootstarp installation.pptx
Kongu Engineering College, Perundurai, Erode
 
PPTX
nested_Object as Parameter & Recursion_Later_commamd.pptx
Kongu Engineering College, Perundurai, Erode
 
PDF
Introduction to Social Media and Social Networks.pdf
Kongu Engineering College, Perundurai, Erode
 
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
Kongu Engineering College, Perundurai, Erode
 
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
Kongu Engineering College, Perundurai, Erode
 
Concepts of Satellite Communication and types and its applications
Kongu Engineering College, Perundurai, Erode
 
Concepts of Mobile Communication Wireless LANs, Bluetooth , HiperLAN
Kongu Engineering College, Perundurai, Erode
 
Web Technology Introduction framework.pptx
Kongu Engineering College, Perundurai, Erode
 
Computer Network - Unicast Routing Distance vector Link state vector
Kongu Engineering College, Perundurai, Erode
 
Android SQLite database oriented application development
Kongu Engineering College, Perundurai, Erode
 
Android Application Development Programming
Kongu Engineering College, Perundurai, Erode
 
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...
Kongu Engineering College, Perundurai, Erode
 
SOA and Monolith Architecture - Micro Services.pptx
Kongu Engineering College, Perundurai, Erode
 
Connect to NoSQL Database using Node JS.pptx
Kongu Engineering College, Perundurai, Erode
 
nested_Object as Parameter & Recursion_Later_commamd.pptx
Kongu Engineering College, Perundurai, Erode
 
Introduction to Social Media and Social Networks.pdf
Kongu Engineering College, Perundurai, Erode
 
Ad

Recently uploaded (20)

PDF
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PPTX
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
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);