SlideShare una empresa de Scribd logo
1 de 7
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

Más contenido relacionado

La actualidad más candente

3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don'tF5 Buddy
 
Node js - Enterprise Class
Node js - Enterprise ClassNode js - Enterprise Class
Node js - Enterprise ClassGlenn Block
 
Simple hack: use multiple mongodb databases in a nodejs express mongodb appli...
Simple hack: use multiple mongodb databases in a nodejs express mongodb appli...Simple hack: use multiple mongodb databases in a nodejs express mongodb appli...
Simple hack: use multiple mongodb databases in a nodejs express mongodb appli...Manoj Mohanan
 
Create a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBCreate a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBHengki Sihombing
 
MongoDB on Windows Azure
MongoDB on Windows AzureMongoDB on Windows Azure
MongoDB on Windows AzureMongoDB
 
MongoDB Israel June Meetup
MongoDB Israel June MeetupMongoDB Israel June Meetup
MongoDB Israel June MeetupValeri Karpov
 
Scalable Architecture 101
Scalable Architecture 101Scalable Architecture 101
Scalable Architecture 101Mike Willbanks
 
Webserver
WebserverWebserver
WebserverARYA TM
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Ayes Chinmay
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 
MongoDB at RubyEnRails 2009
MongoDB at RubyEnRails 2009MongoDB at RubyEnRails 2009
MongoDB at RubyEnRails 2009Mike Dirolf
 
Getting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.jsGetting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.jsGrant Goodale
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generationEleonora Ciceri
 

La actualidad más candente (20)

Node js
Node jsNode js
Node js
 
3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't
 
Node js crash course session 5
Node js crash course   session 5Node js crash course   session 5
Node js crash course session 5
 
Node js - Enterprise Class
Node js - Enterprise ClassNode js - Enterprise Class
Node js - Enterprise Class
 
NodeJS
NodeJSNodeJS
NodeJS
 
Simple hack: use multiple mongodb databases in a nodejs express mongodb appli...
Simple hack: use multiple mongodb databases in a nodejs express mongodb appli...Simple hack: use multiple mongodb databases in a nodejs express mongodb appli...
Simple hack: use multiple mongodb databases in a nodejs express mongodb appli...
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
Create a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBCreate a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDB
 
MongoDB on Windows Azure
MongoDB on Windows AzureMongoDB on Windows Azure
MongoDB on Windows Azure
 
MongoDB Israel June Meetup
MongoDB Israel June MeetupMongoDB Israel June Meetup
MongoDB Israel June Meetup
 
Scalable Architecture 101
Scalable Architecture 101Scalable Architecture 101
Scalable Architecture 101
 
Node intro
Node introNode intro
Node intro
 
Webserver
WebserverWebserver
Webserver
 
Nodejs
NodejsNodejs
Nodejs
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
MongoDB at RubyEnRails 2009
MongoDB at RubyEnRails 2009MongoDB at RubyEnRails 2009
MongoDB at RubyEnRails 2009
 
Nodeconf npm 2011
Nodeconf npm 2011Nodeconf npm 2011
Nodeconf npm 2011
 
Getting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.jsGetting Started with MongoDB and Node.js
Getting Started with MongoDB and Node.js
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 

Destacado

Destacado (6)

Sharada_Resume
Sharada_ResumeSharada_Resume
Sharada_Resume
 
Tushar_Kale_Resume
Tushar_Kale_ResumeTushar_Kale_Resume
Tushar_Kale_Resume
 
Bharath
BharathBharath
Bharath
 
BALA-Resume
BALA-ResumeBALA-Resume
BALA-Resume
 
Diwyanshu Tomar_CV_UI Developer
Diwyanshu Tomar_CV_UI DeveloperDiwyanshu Tomar_CV_UI Developer
Diwyanshu Tomar_CV_UI Developer
 
SAIKIRAN PANJALA RESUME
SAIKIRAN PANJALA RESUMESAIKIRAN PANJALA RESUME
SAIKIRAN PANJALA RESUME
 

Similar a Node js getting started

Similar a Node js getting started (20)

node js.pptx
node js.pptxnode js.pptx
node js.pptx
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
 
5.node js
5.node js5.node js
5.node js
 
Starting with Node.js
Starting with Node.jsStarting with Node.js
Starting with Node.js
 
Basic API Creation with Node.JS
Basic API Creation with Node.JSBasic API Creation with Node.JS
Basic API Creation with Node.JS
 
Web Server and how we can design app in C#
Web Server and how we can design app  in C#Web Server and how we can design app  in C#
Web Server and how we can design app in C#
 
node_js.pptx
node_js.pptxnode_js.pptx
node_js.pptx
 
Node_basics.pptx
Node_basics.pptxNode_basics.pptx
Node_basics.pptx
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Getting started with node JS
Getting started with node JSGetting started with node JS
Getting started with node JS
 
Express node js
Express node jsExpress node js
Express node js
 
Node JS Core Module PowerPoint Presentation
Node JS Core Module PowerPoint PresentationNode JS Core Module PowerPoint Presentation
Node JS Core Module PowerPoint Presentation
 
Node JS
Node JSNode JS
Node JS
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
 
asp_intro.pptx
asp_intro.pptxasp_intro.pptx
asp_intro.pptx
 
Active Server Page - ( ASP )
Active Server Page - ( ASP )Active Server Page - ( ASP )
Active Server Page - ( ASP )
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Hbase coprocessor with Oozie WF referencing 3rd Party jars
Hbase coprocessor with Oozie WF referencing 3rd Party jarsHbase coprocessor with Oozie WF referencing 3rd Party jars
Hbase coprocessor with Oozie WF referencing 3rd Party jars
 

Más de Pallavi Srivastava

Más de Pallavi Srivastava (8)

Various Types of Vendors that Exist in the Software Ecosystem
Various Types of Vendors that Exist in the Software EcosystemVarious Types of Vendors that Exist in the Software Ecosystem
Various Types of Vendors that Exist in the Software Ecosystem
 
ISR Project - Education to underprivileged
ISR Project - Education to underprivilegedISR Project - Education to underprivileged
ISR Project - Education to underprivileged
 
We like project
We like projectWe like project
We like project
 
Java Docs
Java DocsJava Docs
Java Docs
 
Mongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node jsMongoose getting started-Mongo Db with Node js
Mongoose getting started-Mongo Db with Node js
 
Smart dust
Smart dustSmart dust
Smart dust
 
Summer Training report at TATA CMC
Summer Training report at TATA CMCSummer Training report at TATA CMC
Summer Training report at TATA CMC
 
Semantic web
Semantic web Semantic web
Semantic web
 

Último

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 

Último (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

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