SlideShare a Scribd company logo
Node Js
http://www.nodebeginner.org/
“Hello World”
1. Create a file called helloworld.js.
2. We want it to write "Hello World" to STDOUT, and here is the code needed to do that:
3. console.log("Hello World");
4. Save the file, and execute it through Node.js:
node helloworld.js
The application stack
 We want to serve web pages, therefore we need an HTTP server
 Our server will need to answer differently to requests, depending on which URL the
request was asking for, thus we need some kind of router in order to map requests to
request handlers
 To fullfill the requests that arrived at the server and have been routed using the router,
we need actual request handlers
 The router probably should also treat any incoming POST data and give it to the request
handlers in a convenient form, thus we need request data handling
 We not only want to handle requests for URLs, we also want to display content when
these URLs are requested, which means we need some kind of view logic the request
handlers can use in order to send content to the user's browser
 Last but not least, the user will be able to upload images, so we are going to need some
kind of upload handling which takes care of the details
With Node.js, we not only implement our application, we also implement the whole HTTP
server. In fact, our web application and its web server are basically the same.
Building the application stack
A basic HT TPserver
1. Let’s create a main file which we use to start our application, and a module file where our HTTP
servercode lives. Let's start with the server module. Create the file server.js in the rootdirectory
of your project, and fill it with the following code:
2. var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
3. First, execute your script with Node.js:
4. node server.js
5. Now, open your browserand point it at http://localhost:8888/. This should display a web page
that says "Hello World".
The first line requires the http module that ships with Node.js and makes it accessible through the
variable http. We then call one of the functions the http module offers: createServer. This function
returns an object, and this objecthas a method named listen, and takes a numeric value which indicates
the port number our HTTP server is going to listen on.
We could have written the code that starts our server and makes it listen at port 8888 like this:
var http = require("http");
var server = http.createServer();
server.listen(8888);
That would start an HTTP serverlistening at port 8888 and doing nothing else (not even answering any
incoming requests).
How function passing makes our HTTP server work
With this knowledge, let's get back to our minimalistic HTTP server:
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
By now it should be clear what we are actually doing here: we pass the createServer function an
anonymous function. We could achieve the same by refactoring our code to:
var http = require("http");
function onRequest(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
Finding a place for our server module
We have the code for a very basic HTTP server in the file server.js, it's common to have a main file
called index.js which is used to bootstrap and start our application by making use ofthe other modules of
the application (like the HTTP server module that lives in server.js).
Let's talk about how to make server.js a real Node.js module that can be used by our yet -to-be-
written index.js main file.
As you may have noticed, we already used modules in our code, like this:
var http = require("http");
...
http.createServer(...);
It's common practice to choosethe name ofthe module for the name ofthe local variable, but we are free
to choose whatever we like:
var foo = require("http");
...
foo.createServer(...);
Let's find out by turning our server.js script into a real module.
Making some code a module means we need to export those parts of its functionality that we want to
provide to scripts that require our module.
For now, the functionality our HTTP server needs to exportis simple:scripts requiring ourserver module
simply need to start the server.
1. To make this possible, we will put our servercode into a function named start, and we will export
this function:
var http = require("http");
function start() {
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
2. This way, we can now createour main file index.js, and start our HTTP there, although the code
for the server is still in our server.js file.
3. Create a file index.js with the following content:
var server = require("./server");
server.start();
As you can see, we can use our server module just like any internal module: by requiring its file and
assigning it to a variable, its exported functions become available to us.
That's it. We can now start our app via our main script, and it still does exactly the same:
node index.js
Great, we now can put the different parts ofour application into different files and wire them together by
making them modules.
Express
Express is a minimal and flexible Node.js web application framework that provides a robust set offeatures
for web and mobile applications.
Hello world example
Here is an example of a very basic Express app.
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
The req (request) and res (response) are the exact same objects thatNode provides,so you can
invoke req.pipe(), req.on('data', callback) and anything else you would do withoutExpress
involved.
The app starts a server and listens on port 3000 for connection. It will respond with "Hello World!" for
requests to the homepage. For every other path, it will respond with a 404 Not Found.
Save the code in a file named app.js and run it with the following command.
$ node app.js
Then, load http://localhost:3000/ in a browser to see the output.
http://expressjs.com/3x/api.html#express

More Related Content

PDF
Node Js, AngularJs and Express Js Tutorial
PHP Support
 
PDF
Node js first look - 2016
Yauheni Nikanovich
 
PPTX
A slightly advanced introduction to node.js
Sudar Muthu
 
PPT
Node js
Chirag Parmar
 
PPT
Node js
umesh patil
 
PPT
Node js Modules and Event Emitters
TheCreativedev Blog
 
PPTX
Nodejs server lesson 3
SamuelAdetunji2
 
PDF
Node JS Crash Course
Haim Michael
 
Node Js, AngularJs and Express Js Tutorial
PHP Support
 
Node js first look - 2016
Yauheni Nikanovich
 
A slightly advanced introduction to node.js
Sudar Muthu
 
Node js
Chirag Parmar
 
Node js
umesh patil
 
Node js Modules and Event Emitters
TheCreativedev Blog
 
Nodejs server lesson 3
SamuelAdetunji2
 
Node JS Crash Course
Haim Michael
 

What's hot (20)

PPTX
3 Things Everyone Knows About Node JS That You Don't
F5 Buddy
 
PPTX
Node js crash course session 5
Abdul Rahman Masri Attal
 
PPTX
Node js - Enterprise Class
Glenn Block
 
PPTX
NodeJS
Alok Guha
 
PPTX
Simple hack: use multiple mongodb databases in a nodejs express mongodb appli...
Manoj Mohanan
 
PPT
Node.js Express Framework
TheCreativedev Blog
 
PDF
Create a RESTful API with NodeJS, Express and MongoDB
Hengki Sihombing
 
PPTX
MongoDB on Windows Azure
MongoDB
 
PDF
MongoDB Israel June Meetup
Valeri Karpov
 
ODP
Scalable Architecture 101
Mike Willbanks
 
PDF
Node intro
Vishal Sharma
 
PDF
Webserver
ARYA TM
 
PPTX
Nodejs
Akhil Gopan
 
PPTX
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Ayes Chinmay
 
PDF
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
KEY
MongoDB at RubyEnRails 2009
Mike Dirolf
 
KEY
Nodeconf npm 2011
Florent Jaby ヅ
 
KEY
Getting Started with MongoDB and Node.js
Grant Goodale
 
PDF
Dynamic content generation
Eleonora Ciceri
 
3 Things Everyone Knows About Node JS That You Don't
F5 Buddy
 
Node js crash course session 5
Abdul Rahman Masri Attal
 
Node js - Enterprise Class
Glenn Block
 
NodeJS
Alok Guha
 
Simple hack: use multiple mongodb databases in a nodejs express mongodb appli...
Manoj Mohanan
 
Node.js Express Framework
TheCreativedev Blog
 
Create a RESTful API with NodeJS, Express and MongoDB
Hengki Sihombing
 
MongoDB on Windows Azure
MongoDB
 
MongoDB Israel June Meetup
Valeri Karpov
 
Scalable Architecture 101
Mike Willbanks
 
Node intro
Vishal Sharma
 
Webserver
ARYA TM
 
Nodejs
Akhil Gopan
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Ayes Chinmay
 
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
MongoDB at RubyEnRails 2009
Mike Dirolf
 
Nodeconf npm 2011
Florent Jaby ヅ
 
Getting Started with MongoDB and Node.js
Grant Goodale
 
Dynamic content generation
Eleonora Ciceri
 
Ad

Viewers also liked (6)

DOCX
Sharada_Resume
Sharada Nandikolmat
 
PDF
Tushar_Kale_Resume
Tushar Kale
 
DOC
Bharath
jangam bharath
 
DOC
BALA-Resume
Bala kumaran
 
DOC
Diwyanshu Tomar_CV_UI Developer
diwyanshu
 
DOCX
SAIKIRAN PANJALA RESUME
Saikiran Panjala
 
Sharada_Resume
Sharada Nandikolmat
 
Tushar_Kale_Resume
Tushar Kale
 
BALA-Resume
Bala kumaran
 
Diwyanshu Tomar_CV_UI Developer
diwyanshu
 
SAIKIRAN PANJALA RESUME
Saikiran Panjala
 
Ad

Similar to Node js getting started (20)

PPTX
Node.js web-based Example :Run a local server in order to start using node.js...
Kongu Engineering College, Perundurai, Erode
 
PPTX
Scalable network applications, event-driven - Node JS
Cosmin Mereuta
 
ODP
An Overview of Node.js
Ayush Mishra
 
PDF
5.node js
Geunhyung Kim
 
PPTX
Starting with Node.js
Jitendra Zaa
 
PDF
Basic API Creation with Node.JS
Azilen Technologies Pvt. Ltd.
 
PDF
Web Server and how we can design app in C#
caohansnnuedu
 
PPTX
node_js.pptx
dipen55
 
PPTX
Introduction to node.js
Adrien Guéret
 
PDF
Node.js introduction
Parth Joshi
 
PDF
Getting started with node JS
Hamdi Hmidi
 
PDF
Express node js
Yashprit Singh
 
PPTX
Node JS Core Module PowerPoint Presentation
rajeshkannan750222
 
PPTX
node.js.pptx
rani marri
 
PPTX
asp_intro.pptx
vijayalakshmi257551
 
PPTX
Active Server Page - ( ASP )
MohitJoshi154
 
PDF
Bt0083 server side programing
Techglyphs
 
Node.js web-based Example :Run a local server in order to start using node.js...
Kongu Engineering College, Perundurai, Erode
 
Scalable network applications, event-driven - Node JS
Cosmin Mereuta
 
An Overview of Node.js
Ayush Mishra
 
5.node js
Geunhyung Kim
 
Starting with Node.js
Jitendra Zaa
 
Basic API Creation with Node.JS
Azilen Technologies Pvt. Ltd.
 
Web Server and how we can design app in C#
caohansnnuedu
 
node_js.pptx
dipen55
 
Introduction to node.js
Adrien Guéret
 
Node.js introduction
Parth Joshi
 
Getting started with node JS
Hamdi Hmidi
 
Express node js
Yashprit Singh
 
Node JS Core Module PowerPoint Presentation
rajeshkannan750222
 
node.js.pptx
rani marri
 
asp_intro.pptx
vijayalakshmi257551
 
Active Server Page - ( ASP )
MohitJoshi154
 
Bt0083 server side programing
Techglyphs
 

More from Pallavi Srivastava (8)

PDF
Various Types of Vendors that Exist in the Software Ecosystem
Pallavi Srivastava
 
DOCX
ISR Project - Education to underprivileged
Pallavi Srivastava
 
PPTX
We like project
Pallavi Srivastava
 
PPTX
Java Docs
Pallavi Srivastava
 
DOCX
Mongoose getting started-Mongo Db with Node js
Pallavi Srivastava
 
PPTX
Smart dust
Pallavi Srivastava
 
PDF
Summer Training report at TATA CMC
Pallavi Srivastava
 
PPTX
Semantic web
Pallavi Srivastava
 
Various Types of Vendors that Exist in the Software Ecosystem
Pallavi Srivastava
 
ISR Project - Education to underprivileged
Pallavi Srivastava
 
We like project
Pallavi Srivastava
 
Mongoose getting started-Mongo Db with Node js
Pallavi Srivastava
 
Smart dust
Pallavi Srivastava
 
Summer Training report at TATA CMC
Pallavi Srivastava
 
Semantic web
Pallavi Srivastava
 

Recently uploaded (20)

PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
This slide provides an overview Technology
mineshkharadi333
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Doc9.....................................
SofiaCollazos
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 

Node js getting started

  • 1. Node Js http://www.nodebeginner.org/ “Hello World” 1. Create a file called helloworld.js. 2. We want it to write "Hello World" to STDOUT, and here is the code needed to do that: 3. console.log("Hello World"); 4. Save the file, and execute it through Node.js: node helloworld.js The application stack  We want to serve web pages, therefore we need an HTTP server  Our server will need to answer differently to requests, depending on which URL the request was asking for, thus we need some kind of router in order to map requests to request handlers  To fullfill the requests that arrived at the server and have been routed using the router, we need actual request handlers  The router probably should also treat any incoming POST data and give it to the request handlers in a convenient form, thus we need request data handling  We not only want to handle requests for URLs, we also want to display content when these URLs are requested, which means we need some kind of view logic the request handlers can use in order to send content to the user's browser  Last but not least, the user will be able to upload images, so we are going to need some kind of upload handling which takes care of the details With Node.js, we not only implement our application, we also implement the whole HTTP server. In fact, our web application and its web server are basically the same.
  • 2. Building the application stack A basic HT TPserver 1. Let’s create a main file which we use to start our application, and a module file where our HTTP servercode lives. Let's start with the server module. Create the file server.js in the rootdirectory of your project, and fill it with the following code: 2. var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888); 3. First, execute your script with Node.js: 4. node server.js 5. Now, open your browserand point it at http://localhost:8888/. This should display a web page that says "Hello World". The first line requires the http module that ships with Node.js and makes it accessible through the variable http. We then call one of the functions the http module offers: createServer. This function returns an object, and this objecthas a method named listen, and takes a numeric value which indicates the port number our HTTP server is going to listen on. We could have written the code that starts our server and makes it listen at port 8888 like this:
  • 3. var http = require("http"); var server = http.createServer(); server.listen(8888); That would start an HTTP serverlistening at port 8888 and doing nothing else (not even answering any incoming requests). How function passing makes our HTTP server work With this knowledge, let's get back to our minimalistic HTTP server: var http = require("http"); http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888); By now it should be clear what we are actually doing here: we pass the createServer function an anonymous function. We could achieve the same by refactoring our code to: var http = require("http"); function onRequest(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }
  • 4. http.createServer(onRequest).listen(8888); Finding a place for our server module We have the code for a very basic HTTP server in the file server.js, it's common to have a main file called index.js which is used to bootstrap and start our application by making use ofthe other modules of the application (like the HTTP server module that lives in server.js). Let's talk about how to make server.js a real Node.js module that can be used by our yet -to-be- written index.js main file. As you may have noticed, we already used modules in our code, like this: var http = require("http"); ... http.createServer(...); It's common practice to choosethe name ofthe module for the name ofthe local variable, but we are free to choose whatever we like: var foo = require("http"); ... foo.createServer(...);
  • 5. Let's find out by turning our server.js script into a real module. Making some code a module means we need to export those parts of its functionality that we want to provide to scripts that require our module. For now, the functionality our HTTP server needs to exportis simple:scripts requiring ourserver module simply need to start the server. 1. To make this possible, we will put our servercode into a function named start, and we will export this function: var http = require("http"); function start() { function onRequest(request, response) { console.log("Request received."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start; 2. This way, we can now createour main file index.js, and start our HTTP there, although the code for the server is still in our server.js file. 3. Create a file index.js with the following content:
  • 6. var server = require("./server"); server.start(); As you can see, we can use our server module just like any internal module: by requiring its file and assigning it to a variable, its exported functions become available to us. That's it. We can now start our app via our main script, and it still does exactly the same: node index.js Great, we now can put the different parts ofour application into different files and wire them together by making them modules. Express Express is a minimal and flexible Node.js web application framework that provides a robust set offeatures for web and mobile applications. Hello world example Here is an example of a very basic Express app. var express = require('express') var app = express() app.get('/', function (req, res) {
  • 7. res.send('Hello World!') }) var server = app.listen(3000, function () { var host = server.address().address var port = server.address().port console.log('Example app listening at http://%s:%s', host, port) }) The req (request) and res (response) are the exact same objects thatNode provides,so you can invoke req.pipe(), req.on('data', callback) and anything else you would do withoutExpress involved. The app starts a server and listens on port 3000 for connection. It will respond with "Hello World!" for requests to the homepage. For every other path, it will respond with a 404 Not Found. Save the code in a file named app.js and run it with the following command. $ node app.js Then, load http://localhost:3000/ in a browser to see the output. http://expressjs.com/3x/api.html#express