SlideShare a Scribd company logo
THE SERVER-SIDE JAVASCRIPT
● Description
● Introduction
● Some (Confusing) Theory
● 4 Examples
● A couple of weird diagrams
● 2 Pics showing unbelievable benchmarks
● Some stuff from Internet
● And Homer Simpson
Agenda
Description
● V8 is an open source JavaScript engine developed by Google. Its written
in C++ and is used in Google Chrome Browser.
● Node.js runs on V8.
● It was created by Ryan Dahl in 2009.
● Is still in Beta phase. Latest version is 0.6.11
● Is Open Source. It runs well on Linux systems, can also run on Windows
systems.
● If you have worked on EventMachine (Ruby) or Python’s Twisted or Perl’s
AnyEvent framework then following presentation is going to be very easy.
Introduction
● In simple words Node.js is ‘server-side JavaScript’.
● In not-so-simple words Node.js is a high-performance network
applications framework, well optimized for high concurrent environments.
● It’s a command line tool.
● In ‘Node.js’ , ‘.js’ doesn’t mean that its solely written JavaScript. It is 40%
JS and 60% C++.
● From the official site:
‘Node's goal is to provide an easy way to build scalable network programs’ -
(from nodejs.org!)
Introduction: Advanced (& Confusing)
● Node.js uses an event-driven, non-blocking I/O model, which makes it
lightweight. (from nodejs.org!)
● It makes use of event-loops via JavaScript’s callback functionality to
implement the non-blocking I/O.
● Programs for Node.js are written in JavaScript but not in the same
JavaScript we are use to. There is no DOM implementation provided by
Node.js, i.e. you can not do this:
var element = document.getElementById(“elementId”);
● Everything inside Node.js runs in a single-thread.
● Single Threaded :
Node use a single thread to run instead of other server like Apache HTTP who spawn a thread
per request, this approach result in avoiding CPU context switching and massive execution
stacks in memory. This is also the method used by nginx and other servers developed to counter
the C10K problem.
● Event Loop :
Written in C++ using the Marc Lehman’s libev library, the event loop use epoll or kqueue for
scalable event notification mechanism.
● Non blocking I/O :
Node avoid CPU time loss usually made by waiting for an input or an output response
(database, file system, web service, ...) thanks to the full-featured asynchronous I/O provided by
Marc Lehmann’s libeio library.
These characteristics allow Node to handle a large amount of traffic by handling as quickly as
possible a request to free the thread for the next one.
Node has a built-in support for most important protocols like TCP, DNS, and HTTP (the one
that we will focus on). The design goal of a Node application is that any function performing
an I/O must use a callback. That’s why there is no blocking methods provided in Node’s
API.
Example-1: Getting Started & Hello
World● Install/build Node.js.
● (Yes! Windows installer is available!)
● Open your favorite editor and start typing JavaScript.
● When you are done, open cmd/terminal and type this:
‘node YOUR_FILE.js’
● Here is a simple example, which prints ‘hello world’
var sys = require(“sys”);
setTimeout(function(){
sys.puts(“world”);},3000);
sys.puts(“hello”);
//it prints ‘hello’ first and waits for 3 seconds and
then prints ‘world’
Some Theory: Event-loops & Architecture
● Event-loops are the core of event-driven programming, almost all
the UI programs use event-loops to track the user event, for
example: Clicks, Ajax Requests etc.
Client
Event loop
(main thread)
C++
Threadpool
(worker
threads)
Clients send HTTP
requests
to Node.js server
An Event-loop is woken up by
OS,
passes request and response
objects
to the thread-pool
Long-running jobs
run
on worker threads
Response is sent
back to main
thread
via callback
Event loop
returns
result to client
Some Theory: Non-Blocking I/O
● Traditional I/O
var result = db.query(“select x from table_Y”);
doSomethingWith(result); //wait for result!
doSomethingWithOutResult(); //execution is blocked!
● Non-traditional, Non-blocking I/O
db.query(“select x from table_Y”,function (result){
doSomethingWith(result); //wait for result!
});
doSomethingWithOutResult(); //executes without any delay!
Node.js Server VS Multi Threaded Server
What can you do with Node.js ?
● You can create an HTTP server and print ‘hello world’ on the browser in just
4 lines of JavaScript. (Example included)
● You can create a TCP server similar to HTTP server, in just 4 lines of
JavaScript. (Example included)
● You can create a DNS server.
● You can create a Static File Server.
● You can create a Web Chat Application like GTalk in the browser.
● Node.js can also be used for creating online games, collaboration tools or
anything which sends updates to the user in real-time.
Example -2 &3 (HTTP Server & TCP
Server)
● Following code creates an HTTP Server and prints ‘Hello World’ on the browser:
// Load the http module to create an http server.
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Worldn');
});
// Listen on port 5000, IP defaults to 127.0.0.1
server.listen(5000, "127.0.0.1");
How to Run A Http Example:
CMD ->Node Filename.js o/p-> Open Browser and type url
http://hostname:Portnumber For This Example http://127.0.0.1:5000
●Here is an example of a simple TCP server which listens on port 6000 and
echoes whatever you send it:
// Load the http module to create an tcp server.
var net = require('net');
// Configure our TCP server to respond with Echo Sever to all requests.
net.createServer(function (socket) {
socket.write("Echo serverrn");
socket.pipe(socket);
});
// Listen on port 6000, IP defaults to 127.0.0.1
net.listen(6000, "127.0.0.1");
How to Run A Tcp Example:
CMD ->Node Filename.js
o/p-> Open Browser and type url like --
http://hostname:Portnumber
http://127.0.0.1:5000
Node.js Ecosystem
● Node.js heavily relies on modules, in previous examples require keyword
loaded the http & net modules.
● Creating a module is easy, just put your JavaScript code in a separate js
file and include it in your code by using keyword require, like:
var modulex = require(‘./modulex’);
● Libraries in Node.js are called packages and they can be installed by
typing
npm install “package_name”; //package should be available in
npm registry @ nmpjs.org
● NPM (Node Package Manager) comes bundled with Node.js installation.
Example-4: Lets connect to a DB
(MongoDB)
● Install mongojs using npm, a mongoDB driver for Node.js
npm install mongojs
● Code to retrieve all the documents from a collection:
var db = require("mongojs")
.connect("localhost:27017/test", ['test']);
db.test.find({}, function(err, posts) {
if( err || !posts) console.log("No posts found");
else posts.forEach( function(post) {
console.log(post);
});
});
When to use Node.js?
● Node.js is good for creating streaming based real-time services, web chat
applications, static file servers etc.
● If you need high level concurrency and not worried about CPU-cycles.
● If you are great at writing JavaScript code because then you can use the
same language at both the places: server-side and client-side.
● More can be found at: http://stackoverflow.com/questions/5062614/how-
to-decide-when-to-use-nodejs
Some Node.js benchmarksTaken from: http://code.google.com/p/node-js-vs-
apache-php-benchmark/wiki/Tests
A benchmark between Apache+PHP and
node.js, shows the response time for 1000
concurrent connections making 10,000
requests each, for 5 tests.
Taken from:
http://nodejs.org/jsconf2010.pdf
The benchmark shows the
response time in milli-secs
for 4 evented servers.
When to not use Node.js
● When you are doing heavy and CPU intensive calculations on server side,
because event-loops are CPU hungry.
● Node.js API is still in beta, it keeps on changing a lot from one revision to
another and there is a very little backward compatibility. Most of the
packages are also unstable. Therefore is not yet production ready.
● Node.js is a no match for enterprise level application frameworks like
Spring(java), Django(python), Symfony(php) etc. Applications written on
such platforms are meant to be highly user interactive and involve
complex business logic.
● Read further on disadvantages of Node.js on Quora:
http://www.quora.com/What-are-the-disadvantages-of-using-Node-js
Appendix-1: Who is using Node.js in
production?
● Yahoo! : iPad App Livestand uses Yahoo! Manhattan framework which is
based on Node.js.
● LinkedIn : LinkedIn uses a combination of Node.js and MongoDB for its
mobile platform. iOS and Android apps are based on it.
● eBay : Uses Node.js along with ql.io to help application developers in
improving eBay’s end user experience.
● Dow Jones : The WSJ Social front-end is written completely in Node.js,
using Express.js, and many other modules.
● Complete list can be found at:
https://github.com/joyent/node/wiki/Projects,-Applications,-and-
Companies-Using-Node
Appendix-2: Resource to get started
● Watch this video at Youtube:
http://www.youtube.com/watch?v=jo_B4LTHi3I
● Read the free O’reilly Book ‘Up and Running with Node.js’ @
http://ofps.oreilly.com/titles/9781449398583/
● Visit www.nodejs.org for Info/News about Node.js
● Watch Node.js tutorials @ http://nodetuts.com/
● For Info on MongoDB: http://www.mongodb.org/display/DOCS/Home
● For anything else Google!
Appendix-3: Some Good Modules
● Express – to make things simpler e.g. syntax, DB connections.
● Jade – HTML template system
● Socket.IO – to create real-time apps
● Nodemon – to monitor Node.js and push change automatically
● CoffeeScript – for easier JavaScript development
● Find out more about some widely used Node.js modules at:
http://blog.nodejitsu.com/top-node-module-creators
Ad

More Related Content

What's hot (20)

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
AMD Developer Central
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
Bareen Shaikh
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
Gabriele Lana
 
Test driven development in C
Test driven development in CTest driven development in C
Test driven development in C
Amritayan Nayak
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
Apaichon Punopas
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
Ganesh Kondal
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginners
Enoch Joshua
 
Node.js Basics
Node.js Basics Node.js Basics
Node.js Basics
TheCreativedev Blog
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
Node js Introduction
Node js IntroductionNode js Introduction
Node js Introduction
sanskriti agarwal
 
Laravel Events And Queue
Laravel Events And QueueLaravel Events And Queue
Laravel Events And Queue
Vivek S
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
Dmitry Buzdin
 
Java 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgradeJava 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgrade
Simone Bordet
 
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
Edureka!
 
Node ppt
Node pptNode ppt
Node ppt
Tamil Selvan R S
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
orkaplan
 
Angular 2
Angular 2Angular 2
Angular 2
Nigam Goyal
 
Jest
JestJest
Jest
Lucas Lira Gomes
 
JCConf2019: Next Step of JavaScript on Java
JCConf2019: Next Step of JavaScript on JavaJCConf2019: Next Step of JavaScript on Java
JCConf2019: Next Step of JavaScript on Java
Takaaki Sugiyama
 
Node js for beginners
Node js for beginnersNode js for beginners
Node js for beginners
Arjun Sreekumar
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
Bareen Shaikh
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
Gabriele Lana
 
Test driven development in C
Test driven development in CTest driven development in C
Test driven development in C
Amritayan Nayak
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
Ganesh Kondal
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginners
Enoch Joshua
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
Laravel Events And Queue
Laravel Events And QueueLaravel Events And Queue
Laravel Events And Queue
Vivek S
 
Java 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgradeJava 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgrade
Simone Bordet
 
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
Edureka!
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
orkaplan
 
JCConf2019: Next Step of JavaScript on Java
JCConf2019: Next Step of JavaScript on JavaJCConf2019: Next Step of JavaScript on Java
JCConf2019: Next Step of JavaScript on Java
Takaaki Sugiyama
 

Viewers also liked (20)

Yahoo! scale Node.js
Yahoo! scale Node.jsYahoo! scale Node.js
Yahoo! scale Node.js
Fabian Frank
 
North Austin JavaScript User Group Meetup October 2016
North Austin JavaScript User Group Meetup October 2016North Austin JavaScript User Group Meetup October 2016
North Austin JavaScript User Group Meetup October 2016
Brad Bates
 
An Introduction to hapi.js
An Introduction to hapi.jsAn Introduction to hapi.js
An Introduction to hapi.js
Dave Stevens
 
Building an API in Node with HapiJS
Building an API in Node with HapiJSBuilding an API in Node with HapiJS
Building an API in Node with HapiJS
Loc Nguyen
 
Costume mood board
Costume mood boardCostume mood board
Costume mood board
martinacipolla
 
PORTFOLIO2016
PORTFOLIO2016PORTFOLIO2016
PORTFOLIO2016
Jennifer Barnes-Hoyt
 
practicas de las Tics
practicas de las Ticspracticas de las Tics
practicas de las Tics
carolineflordiaz
 
kk-resume
kk-resumekk-resume
kk-resume
Keshav Kumar Thakur
 
Tujuan
TujuanTujuan
Tujuan
Fakhrul Fakhreza
 
Eyezek
EyezekEyezek
Eyezek
Meshack Okao
 
Psychological mood board
Psychological mood boardPsychological mood board
Psychological mood board
martinacipolla
 
Diputados impulsan una ley para "Zonas Libres de Fumigación"
Diputados impulsan una ley para "Zonas Libres de Fumigación"Diputados impulsan una ley para "Zonas Libres de Fumigación"
Diputados impulsan una ley para "Zonas Libres de Fumigación"
Gonzalo Reyes
 
Canal 25-Ayacucho
Canal 25-AyacuchoCanal 25-Ayacucho
Canal 25-Ayacucho
Jairo Brian Gutiérrez Quispe
 
Tarea Nº 8 sobre Malformaciones Genéticas de GyC-JL
Tarea Nº 8 sobre Malformaciones Genéticas de GyC-JLTarea Nº 8 sobre Malformaciones Genéticas de GyC-JL
Tarea Nº 8 sobre Malformaciones Genéticas de GyC-JL
José Luís Dávila Duarte
 
Reprodução medicamente assistida
Reprodução medicamente assistidaReprodução medicamente assistida
Reprodução medicamente assistida
Helena Sousa
 
Searching for the framework of my dreams in node.js ecosystem by Mykyta Semen...
Searching for the framework of my dreams in node.js ecosystem by Mykyta Semen...Searching for the framework of my dreams in node.js ecosystem by Mykyta Semen...
Searching for the framework of my dreams in node.js ecosystem by Mykyta Semen...
Binary Studio
 
La salle in paksitan ashbsjhjk
La salle in paksitan ashbsjhjkLa salle in paksitan ashbsjhjk
La salle in paksitan ashbsjhjk
Amir Raza Fsc
 
Ficha técnica Lipofeed NUPROPEC
Ficha técnica Lipofeed NUPROPECFicha técnica Lipofeed NUPROPEC
Ficha técnica Lipofeed NUPROPEC
Premezclas Energéticas Pecuarias
 
VDSL FOR TRIPLE PLAY
VDSL FOR TRIPLE PLAYVDSL FOR TRIPLE PLAY
VDSL FOR TRIPLE PLAY
fernandomireles
 
Node.js Performance Case Study
Node.js Performance Case StudyNode.js Performance Case Study
Node.js Performance Case Study
Fabian Frank
 
Yahoo! scale Node.js
Yahoo! scale Node.jsYahoo! scale Node.js
Yahoo! scale Node.js
Fabian Frank
 
North Austin JavaScript User Group Meetup October 2016
North Austin JavaScript User Group Meetup October 2016North Austin JavaScript User Group Meetup October 2016
North Austin JavaScript User Group Meetup October 2016
Brad Bates
 
An Introduction to hapi.js
An Introduction to hapi.jsAn Introduction to hapi.js
An Introduction to hapi.js
Dave Stevens
 
Building an API in Node with HapiJS
Building an API in Node with HapiJSBuilding an API in Node with HapiJS
Building an API in Node with HapiJS
Loc Nguyen
 
Psychological mood board
Psychological mood boardPsychological mood board
Psychological mood board
martinacipolla
 
Diputados impulsan una ley para "Zonas Libres de Fumigación"
Diputados impulsan una ley para "Zonas Libres de Fumigación"Diputados impulsan una ley para "Zonas Libres de Fumigación"
Diputados impulsan una ley para "Zonas Libres de Fumigación"
Gonzalo Reyes
 
Tarea Nº 8 sobre Malformaciones Genéticas de GyC-JL
Tarea Nº 8 sobre Malformaciones Genéticas de GyC-JLTarea Nº 8 sobre Malformaciones Genéticas de GyC-JL
Tarea Nº 8 sobre Malformaciones Genéticas de GyC-JL
José Luís Dávila Duarte
 
Reprodução medicamente assistida
Reprodução medicamente assistidaReprodução medicamente assistida
Reprodução medicamente assistida
Helena Sousa
 
Searching for the framework of my dreams in node.js ecosystem by Mykyta Semen...
Searching for the framework of my dreams in node.js ecosystem by Mykyta Semen...Searching for the framework of my dreams in node.js ecosystem by Mykyta Semen...
Searching for the framework of my dreams in node.js ecosystem by Mykyta Semen...
Binary Studio
 
La salle in paksitan ashbsjhjk
La salle in paksitan ashbsjhjkLa salle in paksitan ashbsjhjk
La salle in paksitan ashbsjhjk
Amir Raza Fsc
 
Node.js Performance Case Study
Node.js Performance Case StudyNode.js Performance Case Study
Node.js Performance Case Study
Fabian Frank
 
Ad

Similar to Nodejs (20)

An overview of node.js
An overview of node.jsAn overview of node.js
An overview of node.js
valuebound
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
Ganesh Kondal
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
Khaled Mosharraf
 
Proposal
ProposalProposal
Proposal
Constantine Priemski
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
Node
NodeNode
Node
Ankit Chawla
 
Node js
Node jsNode js
Node js
Chirag Parmar
 
02 Node introduction
02 Node introduction02 Node introduction
02 Node introduction
Ahmed Elbassel
 
Introduction to node.js By Ahmed Assaf
Introduction to node.js  By Ahmed AssafIntroduction to node.js  By Ahmed Assaf
Introduction to node.js By Ahmed Assaf
Ahmed Assaf
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
Nodejs
NodejsNodejs
Nodejs
dssprakash
 
Node js internal
Node js internalNode js internal
Node js internal
Chinh Ngo Nguyen
 
Nodejs web service for starters
Nodejs web service for startersNodejs web service for starters
Nodejs web service for starters
Bruce Li
 
Node.js Presentation
Node.js PresentationNode.js Presentation
Node.js Presentation
Exist
 
Ferrara Linux Day 2011
Ferrara Linux Day 2011Ferrara Linux Day 2011
Ferrara Linux Day 2011
Gianluca Padovani
 
An introduction to Node.js application development
An introduction to Node.js application developmentAn introduction to Node.js application development
An introduction to Node.js application development
shelloidhq
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
drupalcampest
 
Построение простого REST сервера на Node.js | Odessa Frontend Code challenge
Построение простого REST сервера на Node.js | Odessa Frontend Code challengeПостроение простого REST сервера на Node.js | Odessa Frontend Code challenge
Построение простого REST сервера на Node.js | Odessa Frontend Code challenge
OdessaFrontend
 
node.js
node.jsnode.js
node.js
NepalAdz
 
An overview of node.js
An overview of node.jsAn overview of node.js
An overview of node.js
valuebound
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
Ganesh Kondal
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
Introduction to node.js By Ahmed Assaf
Introduction to node.js  By Ahmed AssafIntroduction to node.js  By Ahmed Assaf
Introduction to node.js By Ahmed Assaf
Ahmed Assaf
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
Nodejs web service for starters
Nodejs web service for startersNodejs web service for starters
Nodejs web service for starters
Bruce Li
 
Node.js Presentation
Node.js PresentationNode.js Presentation
Node.js Presentation
Exist
 
An introduction to Node.js application development
An introduction to Node.js application developmentAn introduction to Node.js application development
An introduction to Node.js application development
shelloidhq
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
drupalcampest
 
Построение простого REST сервера на Node.js | Odessa Frontend Code challenge
Построение простого REST сервера на Node.js | Odessa Frontend Code challengeПостроение простого REST сервера на Node.js | Odessa Frontend Code challenge
Построение простого REST сервера на Node.js | Odessa Frontend Code challenge
OdessaFrontend
 
Ad

Recently uploaded (20)

How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
Automation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath CertificateAutomation Techniques in RPA - UiPath Certificate
Automation Techniques in RPA - UiPath Certificate
VICTOR MAESTRE RAMIREZ
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 

Nodejs

  • 2. ● Description ● Introduction ● Some (Confusing) Theory ● 4 Examples ● A couple of weird diagrams ● 2 Pics showing unbelievable benchmarks ● Some stuff from Internet ● And Homer Simpson Agenda
  • 3. Description ● V8 is an open source JavaScript engine developed by Google. Its written in C++ and is used in Google Chrome Browser. ● Node.js runs on V8. ● It was created by Ryan Dahl in 2009. ● Is still in Beta phase. Latest version is 0.6.11 ● Is Open Source. It runs well on Linux systems, can also run on Windows systems. ● If you have worked on EventMachine (Ruby) or Python’s Twisted or Perl’s AnyEvent framework then following presentation is going to be very easy.
  • 4. Introduction ● In simple words Node.js is ‘server-side JavaScript’. ● In not-so-simple words Node.js is a high-performance network applications framework, well optimized for high concurrent environments. ● It’s a command line tool. ● In ‘Node.js’ , ‘.js’ doesn’t mean that its solely written JavaScript. It is 40% JS and 60% C++. ● From the official site: ‘Node's goal is to provide an easy way to build scalable network programs’ - (from nodejs.org!)
  • 5. Introduction: Advanced (& Confusing) ● Node.js uses an event-driven, non-blocking I/O model, which makes it lightweight. (from nodejs.org!) ● It makes use of event-loops via JavaScript’s callback functionality to implement the non-blocking I/O. ● Programs for Node.js are written in JavaScript but not in the same JavaScript we are use to. There is no DOM implementation provided by Node.js, i.e. you can not do this: var element = document.getElementById(“elementId”); ● Everything inside Node.js runs in a single-thread.
  • 6. ● Single Threaded : Node use a single thread to run instead of other server like Apache HTTP who spawn a thread per request, this approach result in avoiding CPU context switching and massive execution stacks in memory. This is also the method used by nginx and other servers developed to counter the C10K problem. ● Event Loop : Written in C++ using the Marc Lehman’s libev library, the event loop use epoll or kqueue for scalable event notification mechanism. ● Non blocking I/O : Node avoid CPU time loss usually made by waiting for an input or an output response (database, file system, web service, ...) thanks to the full-featured asynchronous I/O provided by Marc Lehmann’s libeio library. These characteristics allow Node to handle a large amount of traffic by handling as quickly as possible a request to free the thread for the next one. Node has a built-in support for most important protocols like TCP, DNS, and HTTP (the one that we will focus on). The design goal of a Node application is that any function performing an I/O must use a callback. That’s why there is no blocking methods provided in Node’s API.
  • 7. Example-1: Getting Started & Hello World● Install/build Node.js. ● (Yes! Windows installer is available!) ● Open your favorite editor and start typing JavaScript. ● When you are done, open cmd/terminal and type this: ‘node YOUR_FILE.js’ ● Here is a simple example, which prints ‘hello world’ var sys = require(“sys”); setTimeout(function(){ sys.puts(“world”);},3000); sys.puts(“hello”); //it prints ‘hello’ first and waits for 3 seconds and then prints ‘world’
  • 8. Some Theory: Event-loops & Architecture ● Event-loops are the core of event-driven programming, almost all the UI programs use event-loops to track the user event, for example: Clicks, Ajax Requests etc. Client Event loop (main thread) C++ Threadpool (worker threads) Clients send HTTP requests to Node.js server An Event-loop is woken up by OS, passes request and response objects to the thread-pool Long-running jobs run on worker threads Response is sent back to main thread via callback Event loop returns result to client
  • 9. Some Theory: Non-Blocking I/O ● Traditional I/O var result = db.query(“select x from table_Y”); doSomethingWith(result); //wait for result! doSomethingWithOutResult(); //execution is blocked! ● Non-traditional, Non-blocking I/O db.query(“select x from table_Y”,function (result){ doSomethingWith(result); //wait for result! }); doSomethingWithOutResult(); //executes without any delay!
  • 10. Node.js Server VS Multi Threaded Server
  • 11. What can you do with Node.js ? ● You can create an HTTP server and print ‘hello world’ on the browser in just 4 lines of JavaScript. (Example included) ● You can create a TCP server similar to HTTP server, in just 4 lines of JavaScript. (Example included) ● You can create a DNS server. ● You can create a Static File Server. ● You can create a Web Chat Application like GTalk in the browser. ● Node.js can also be used for creating online games, collaboration tools or anything which sends updates to the user in real-time.
  • 12. Example -2 &3 (HTTP Server & TCP Server) ● Following code creates an HTTP Server and prints ‘Hello World’ on the browser: // Load the http module to create an http server. var http = require('http'); // Configure our HTTP server to respond with Hello World to all requests. http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }); // Listen on port 5000, IP defaults to 127.0.0.1 server.listen(5000, "127.0.0.1"); How to Run A Http Example: CMD ->Node Filename.js o/p-> Open Browser and type url http://hostname:Portnumber For This Example http://127.0.0.1:5000
  • 13. ●Here is an example of a simple TCP server which listens on port 6000 and echoes whatever you send it: // Load the http module to create an tcp server. var net = require('net'); // Configure our TCP server to respond with Echo Sever to all requests. net.createServer(function (socket) { socket.write("Echo serverrn"); socket.pipe(socket); }); // Listen on port 6000, IP defaults to 127.0.0.1 net.listen(6000, "127.0.0.1"); How to Run A Tcp Example: CMD ->Node Filename.js o/p-> Open Browser and type url like -- http://hostname:Portnumber http://127.0.0.1:5000
  • 14. Node.js Ecosystem ● Node.js heavily relies on modules, in previous examples require keyword loaded the http & net modules. ● Creating a module is easy, just put your JavaScript code in a separate js file and include it in your code by using keyword require, like: var modulex = require(‘./modulex’); ● Libraries in Node.js are called packages and they can be installed by typing npm install “package_name”; //package should be available in npm registry @ nmpjs.org ● NPM (Node Package Manager) comes bundled with Node.js installation.
  • 15. Example-4: Lets connect to a DB (MongoDB) ● Install mongojs using npm, a mongoDB driver for Node.js npm install mongojs ● Code to retrieve all the documents from a collection: var db = require("mongojs") .connect("localhost:27017/test", ['test']); db.test.find({}, function(err, posts) { if( err || !posts) console.log("No posts found"); else posts.forEach( function(post) { console.log(post); }); });
  • 16. When to use Node.js? ● Node.js is good for creating streaming based real-time services, web chat applications, static file servers etc. ● If you need high level concurrency and not worried about CPU-cycles. ● If you are great at writing JavaScript code because then you can use the same language at both the places: server-side and client-side. ● More can be found at: http://stackoverflow.com/questions/5062614/how- to-decide-when-to-use-nodejs
  • 17. Some Node.js benchmarksTaken from: http://code.google.com/p/node-js-vs- apache-php-benchmark/wiki/Tests A benchmark between Apache+PHP and node.js, shows the response time for 1000 concurrent connections making 10,000 requests each, for 5 tests. Taken from: http://nodejs.org/jsconf2010.pdf The benchmark shows the response time in milli-secs for 4 evented servers.
  • 18. When to not use Node.js ● When you are doing heavy and CPU intensive calculations on server side, because event-loops are CPU hungry. ● Node.js API is still in beta, it keeps on changing a lot from one revision to another and there is a very little backward compatibility. Most of the packages are also unstable. Therefore is not yet production ready. ● Node.js is a no match for enterprise level application frameworks like Spring(java), Django(python), Symfony(php) etc. Applications written on such platforms are meant to be highly user interactive and involve complex business logic. ● Read further on disadvantages of Node.js on Quora: http://www.quora.com/What-are-the-disadvantages-of-using-Node-js
  • 19. Appendix-1: Who is using Node.js in production? ● Yahoo! : iPad App Livestand uses Yahoo! Manhattan framework which is based on Node.js. ● LinkedIn : LinkedIn uses a combination of Node.js and MongoDB for its mobile platform. iOS and Android apps are based on it. ● eBay : Uses Node.js along with ql.io to help application developers in improving eBay’s end user experience. ● Dow Jones : The WSJ Social front-end is written completely in Node.js, using Express.js, and many other modules. ● Complete list can be found at: https://github.com/joyent/node/wiki/Projects,-Applications,-and- Companies-Using-Node
  • 20. Appendix-2: Resource to get started ● Watch this video at Youtube: http://www.youtube.com/watch?v=jo_B4LTHi3I ● Read the free O’reilly Book ‘Up and Running with Node.js’ @ http://ofps.oreilly.com/titles/9781449398583/ ● Visit www.nodejs.org for Info/News about Node.js ● Watch Node.js tutorials @ http://nodetuts.com/ ● For Info on MongoDB: http://www.mongodb.org/display/DOCS/Home ● For anything else Google!
  • 21. Appendix-3: Some Good Modules ● Express – to make things simpler e.g. syntax, DB connections. ● Jade – HTML template system ● Socket.IO – to create real-time apps ● Nodemon – to monitor Node.js and push change automatically ● CoffeeScript – for easier JavaScript development ● Find out more about some widely used Node.js modules at: http://blog.nodejitsu.com/top-node-module-creators