SlideShare a Scribd company logo
1 of 21
Download to read offline
The Server-side JavaScript


                             Vikash Singh
WHAT TO EXPECT AHEAD….
 Introduction
 Some (Confusing) Theory

 5 Examples

 A couple of weird diagrams

 2 Pics showing unbelievable benchmarks

 Some stuff from Internet

 And Homer Simpson
BACKGROUND
 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: BASIC
 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.
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
      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.        Clients send HTTP requests
                       Client
                                      to Node.js server




Event loop returns                    An Event-loop is woken up by OS,
result to client                      passes request and response objects
                      Event loop      to the thread-pool
                      (main thread)

                                                Long-running jobs run
                                                on worker threads
                                 C++
Response is sent
                             Threadpool
back to main thread
                               (worker
via callback
                              threads)
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!
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:
    var http = require('http');
    http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello Worldn'); }).listen(5000, "127.0.0.1");


   Here is an example of a simple TCP server which
    listens on port 6000 and echoes whatever you send
    it:
    var net = require('net');
    net.createServer(function (socket) {
    socket.write("Echo serverrn");
    socket.pipe(socket); }).listen(6000, "127.0.0.1");
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
EXAMPLE-5: TWITTER STREAMING
   Install nTwitter module using npm:
    Npm install ntwitter
   Code:
    var twitter = require('ntwitter');
    var twit = new twitter({
          consumer_key: ‘c_key’,
          consumer_secret: ‘c_secret’,
          access_token_key: ‘token_key’,
          access_token_secret: ‘token_secret’});
    twit.stream('statuses/sample', function(stream) {
        stream.on('data', function (data) {
          console.log(data); });
    });
Introduction to Node.js
SOME NODE.JS BENCHMARKS
                                   Taken 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-
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
Introduction to Node.js

More Related Content

What's hot

What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?Simplilearn
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JSArno Lordkronos
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsDinesh U
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners Varun Raj
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRob O'Doherty
 
Introduction to MERN Stack
Introduction to MERN StackIntroduction to MERN Stack
Introduction to MERN StackSurya937648
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScriptRavi Bhadauria
 
An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)iFour Technolab Pvt. Ltd.
 

What's hot (20)

Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Flask
FlaskFlask
Flask
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
.Net Core
.Net Core.Net Core
.Net Core
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
Javascript
JavascriptJavascript
Javascript
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Js ppt
Js pptJs ppt
Js ppt
 
Introduction to MERN Stack
Introduction to MERN StackIntroduction to MERN Stack
Introduction to MERN Stack
 
Express js
Express jsExpress js
Express js
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
 
Introduction to NodeJS
Introduction to NodeJSIntroduction to NodeJS
Introduction to NodeJS
 
An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Express JS
Express JSExpress JS
Express JS
 

Viewers also liked

Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture AppDynamics
 
The Enterprise Case for Node.js
The Enterprise Case for Node.jsThe Enterprise Case for Node.js
The Enterprise Case for Node.jsNodejsFoundation
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907NodejsFoundation
 

Viewers also liked (7)

Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Node ppt
Node pptNode ppt
Node ppt
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
The Enterprise Case for Node.js
The Enterprise Case for Node.jsThe Enterprise Case for Node.js
The Enterprise Case for Node.js
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 

Similar to Introduction to Node.js

Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comVan-Duyet Le
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate
 
Day In A Life Of A Node.js Developer
Day In A Life Of A Node.js DeveloperDay In A Life Of A Node.js Developer
Day In A Life Of A Node.js DeveloperEdureka!
 
Day in a life of a node.js developer
Day in a life of a node.js developerDay in a life of a node.js developer
Day in a life of a node.js developerEdureka!
 
An overview of node.js
An overview of node.jsAn overview of node.js
An overview of node.jsvaluebound
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tourcacois
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDDSudar Muthu
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
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 AssafAhmed Assaf
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Ganesh Kondal
 
Why Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiWhy Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiJackson Tian
 

Similar to Introduction to Node.js (20)

Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
 
Proposal
ProposalProposal
Proposal
 
Nodejs
NodejsNodejs
Nodejs
 
Node
NodeNode
Node
 
Nodejs
NodejsNodejs
Nodejs
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect Guide
 
Introduction to Node.JS
Introduction to Node.JSIntroduction to Node.JS
Introduction to Node.JS
 
Day In A Life Of A Node.js Developer
Day In A Life Of A Node.js DeveloperDay In A Life Of A Node.js Developer
Day In A Life Of A Node.js Developer
 
Day in a life of a node.js developer
Day in a life of a node.js developerDay in a life of a node.js developer
Day in a life of a node.js developer
 
An overview of node.js
An overview of node.jsAn overview of node.js
An overview of node.js
 
Node js
Node jsNode js
Node js
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Node js beginner
Node js beginnerNode js beginner
Node js beginner
 
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
 
Ferrara Linux Day 2011
Ferrara Linux Day 2011Ferrara Linux Day 2011
Ferrara Linux Day 2011
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
 
Why Nodejs Guilin Shanghai
Why Nodejs Guilin ShanghaiWhy Nodejs Guilin Shanghai
Why Nodejs Guilin Shanghai
 

Recently uploaded

Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 

Recently uploaded (20)

Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 

Introduction to Node.js

  • 2. WHAT TO EXPECT AHEAD….  Introduction  Some (Confusing) Theory  5 Examples  A couple of weird diagrams  2 Pics showing unbelievable benchmarks  Some stuff from Internet  And Homer Simpson
  • 3. BACKGROUND  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: BASIC  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. 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’
  • 7. SOME THEORY: EVENT-LOOPS  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. Clients send HTTP requests Client to Node.js server Event loop returns An Event-loop is woken up by OS, result to client passes request and response objects Event loop to the thread-pool (main thread) Long-running jobs run on worker threads C++ Response is sent Threadpool back to main thread (worker via callback threads)
  • 8. 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!
  • 9. 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.
  • 10. EXAMPLE -2 &3 (HTTP SERVER & TCP SERVER)  Following code creates an HTTP Server and prints ‘Hello World’ on the browser: var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }).listen(5000, "127.0.0.1");  Here is an example of a simple TCP server which listens on port 6000 and echoes whatever you send it: var net = require('net'); net.createServer(function (socket) { socket.write("Echo serverrn"); socket.pipe(socket); }).listen(6000, "127.0.0.1");
  • 11. 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.
  • 12. 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); }); });
  • 13. 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
  • 14. EXAMPLE-5: TWITTER STREAMING  Install nTwitter module using npm: Npm install ntwitter  Code: var twitter = require('ntwitter'); var twit = new twitter({ consumer_key: ‘c_key’, consumer_secret: ‘c_secret’, access_token_key: ‘token_key’, access_token_secret: ‘token_secret’}); twit.stream('statuses/sample', function(stream) { stream.on('data', function (data) { console.log(data); }); });
  • 16. SOME NODE.JS BENCHMARKS Taken 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.
  • 17. 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-
  • 18. 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
  • 19. 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!
  • 20. 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