SlideShare uma empresa 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

Destaque (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
 

Semelhante a Node js getting started

Semelhante 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
 

Mais de Pallavi Srivastava

Mais 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

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
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
 

Último (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 

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