SlideShare una empresa de Scribd logo
1 de 37
Descargar para leer sin conexión
node.js
 A quick tour




                by Felix Geisendörfer
Introduction
Why?

Node's goal is to provide an easy
way to build scalable network
programs.
                        -- nodejs.org
How?

Keep slow operations from
blocking other operations.
Traditional I/O

var data = file.read('file.txt');
doSomethingWith(data);




  Something is not right here
Traditional I/O

var data = file.read('file.txt');

// zzzZZzzz   FAIL!
doSomethingWith(data);




   Don’t waste those cycles!
Async I/O

file.read('file.txt', function(data) {
  doSomethingWith(data);
});                                   WIN   !
doSomethingElse();




         No need to wait for the disk,
         do something else meanwhile!
The Present
CommonJS Modules
hello.js
exports.world = function() {
   return 'Hello World';
};

main.js
var hello = require('./hello');
var sys = require('sys');
sys.puts(hello.world());


                 $ node main.js
                 Hello World
Child processes
child.js
var child = process.createChildProcess('sh',
['-c', 'echo hello; sleep 1; echo world;']);
child.addListener('output', function (chunk) {
  p(chunk);
});

                $ node child.js
                "hellon"
                # 1 sec delay
                "worldn"
                null
Http Server
var http = require('http');
http.createServer(function(req, res) {
  setTimeout(function() {
    res.sendHeader(200, {'Content-Type': 'text/plain'});
    res.sendBody('Thanks for waiting!');
    res.finish();
  }, 1000);
}).listen(4000);

                $ curl localhost:4000
                # 1 sec delay
                Thanks for waiting!
Tcp Server
var tcp = require('tcp');
tcp.createServer(function(socket) {
  socket.addListener('connect', function() {
    socket.send("Hi, How Are You?n> ");
  });
  socket.addListener('receive', function(data) {
    socket.send(data);
  });
}).listen(4000);

              $ nc localhost 4000
              Hi, How Are You?
              > Great!
              Great!
DNS
dns.js
var dns = require('dns');
dns.resolve4('nodejs.org')
  .addCallback(function(r) {
    p(r);
  });


               $ node dns.js
               [
                 "97.107.132.72"
               ]
Watch File
watch.js
process.watchFile(__filename, function() {
  puts('You changed me!');
  process.exit();
});



                $ node watch.js
                # edit watch.js
                You changed me!
ECMAScript 5
• Getters / setters
var a = {};
a.__defineGetter__('foo', function() {
  return 'bar';
});
puts(a.foo);


• Array: filter, forEach, reduce, etc.

• JSON.stringify(), JSON.parse()
There is only 1 thread
file.read('file.txt', function(data) {
  // Will never fire
});

while (true) {
  // this blocks the entire process
}


         Good for conceptual simplicity
         Bad for CPU-bound algorithms
The Future
Web workers
• Multiple node processes that do
  interprocess communication


• CPU-bound algorithms can run separately

• Multiple CPU cores can be used efficiently
Move C/C++ stuff to JS

• Simplifies the code base

• Makes contributions easier

• Low-level bindings = more flexibility
Better Socket Support
• Support for unix sockets, socketpair(), pipe()

• Pass sockets between processes " load
  balance requests between web workers


• Unified socket streaming interfaces
Even more ...
• Connecting streams
var f = file.writeStream('/tmp/x.txt');
connect(req.body, f);


• Http parser bindings

• No memcpy() for http requests
                             + hot code reloading!
Suitable Applications

• Web frameworks

• Real time

• Crawlers
More Applications

• Process monitoring

• File uploading

• Streaming
Demo Time!
Http Chat in 14 LoC
var
  http = require('http'),
  messages = [];

http.createServer(function(req, res) {
  res.sendHeader(200, {'Content-Type' : 'text/plain'});
  if (req.url == '/') {
    res.sendBody(messages.join("n"));
  } else if (req.url !== '/favicon.ico') {
    messages.push(decodeURIComponent(req.url.substr(1)));
    res.sendBody('ok!');
  }
  res.finish();
}).listen(4000);
The chat room:

  http://debuggable.com:4000/

          Send a message:

http://debuggable.com:4000/<msg>
Questions?




✎   @felixge
$   http://debuggable.com/
Bonus Slides!
Dirty




NoSQL for the little man!
Dirty



JavaScript Views            Memory Store
Disk Persistence            Speed > Safety


                    Dirty
Dirty Hello World
hello.js
var
  Dirty = require('../lib/dirty').Dirty,
  posts = new Dirty('test.dirty');

posts.add({hello: 'dirty world!'});
posts.set('my-key', {looks: 'nice'});


    $ node hello.js
    $ cat test.dirty
    {"hello":"dirty world!","_key":"3b8f86..."}
    {"looks":"nice","_key":"my-key"}
Reloading from Disk
hello.js
var
  Dirty = require('../lib/dirty').Dirty,
  posts = new Dirty('test.dirty');

posts.load()
  .addCallback(function() {
    p(posts.get('my-key'));
  });


           $ node hello.js
           {"looks": "nice", "_key": "my-key"}
Filtering records
hello.js
var
  Dirty = require('../lib/dirty').Dirty,
  posts = new Dirty('test.dirty');

posts.load()
  .addCallback(function() {
    var docs = posts.filter(function(doc) {
      return ('hello' in doc);
    });
    p(docs);
  });

 $ node hello.js
[{"hello": "dirty world!", "_key": "3b8f86..."}]
Benchmarks


Do your own!
My Results

• Set: 100k docs / sec

• Iterate: 33 million docs / sec

• Filter: 14 million docs / sec
      (on my laptop - your milage may vary)
Use Cases

• Small projects (db < memory)

• Rapid prototyping

• Add HTTP/TCP interface and scale
http://github.com/felixge/node-dirty



   (or google for “dirty felixge”)

Más contenido relacionado

La actualidad más candente

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
Introduction to node.jsIntroduction to node.js
Introduction to node.jsjacekbecela
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsMarcus Frödin
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.jsConFoo
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & ExpressChristian Joudrey
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)Felix Geisendörfer
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node jsfakedarren
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming Tom Croucher
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)Chris Cowan
 

La actualidad más candente (20)

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 ppt
Node pptNode ppt
Node ppt
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Node.js in production
Node.js in productionNode.js in production
Node.js in production
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
NodeJS
NodeJSNodeJS
NodeJS
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
 
Building your first Node app with Connect & Express
Building your first Node app with Connect & ExpressBuilding your first Node app with Connect & Express
Building your first Node app with Connect & Express
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
 
Building a real life application in node js
Building a real life application in node jsBuilding a real life application in node js
Building a real life application in node js
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Node.js
Node.jsNode.js
Node.js
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)Nodejs - A quick tour (v4)
Nodejs - A quick tour (v4)
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 

Destacado

Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
 
Create simple api using node js
Create simple api using node jsCreate simple api using node js
Create simple api using node jsEdwin Andrianto
 
Getting Started with the Node.js LoopBack APi Framework
Getting Started with the Node.js LoopBack APi FrameworkGetting Started with the Node.js LoopBack APi Framework
Getting Started with the Node.js LoopBack APi FrameworkJimmy Guerrero
 
Building a Node.js API backend with LoopBack in 5 Minutes
Building a Node.js API backend with LoopBack in 5 MinutesBuilding a Node.js API backend with LoopBack in 5 Minutes
Building a Node.js API backend with LoopBack in 5 MinutesRaymond Feng
 
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
 
Microservices with Node.js and RabbitMQ
Microservices with Node.js and RabbitMQMicroservices with Node.js and RabbitMQ
Microservices with Node.js and RabbitMQPaulius Uza
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907NodejsFoundation
 

Destacado (10)

Node.js гэж юу вэ?
Node.js гэж юу вэ?Node.js гэж юу вэ?
Node.js гэж юу вэ?
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Create simple api using node js
Create simple api using node jsCreate simple api using node js
Create simple api using node js
 
Top Node.js Metrics to Watch
Top Node.js Metrics to WatchTop Node.js Metrics to Watch
Top Node.js Metrics to Watch
 
Getting Started with the Node.js LoopBack APi Framework
Getting Started with the Node.js LoopBack APi FrameworkGetting Started with the Node.js LoopBack APi Framework
Getting Started with the Node.js LoopBack APi Framework
 
Building a Node.js API backend with LoopBack in 5 Minutes
Building a Node.js API backend with LoopBack in 5 MinutesBuilding a Node.js API backend with LoopBack in 5 Minutes
Building a Node.js API backend with LoopBack in 5 Minutes
 
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
 
Microservices with Node.js and RabbitMQ
Microservices with Node.js and RabbitMQMicroservices with Node.js and RabbitMQ
Microservices with Node.js and RabbitMQ
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 

Similar a Node.js - A Quick Tour

Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}.toster
 
Express Presentation
Express PresentationExpress Presentation
Express Presentationaaronheckmann
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsDerek Anderson
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsOhad Kravchick
 
Background Tasks in Node - Evan Tahler, TaskRabbit
Background Tasks in Node - Evan Tahler, TaskRabbitBackground Tasks in Node - Evan Tahler, TaskRabbit
Background Tasks in Node - Evan Tahler, TaskRabbitRedis Labs
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETGianluca Carucci
 
Make BDD great again
Make BDD great againMake BDD great again
Make BDD great againYana Gusti
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.Mike Brevoort
 
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 talkAarti Parikh
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPMariano Iglesias
 

Similar a Node.js - A Quick Tour (20)

node.js dao
node.js daonode.js dao
node.js dao
 
Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3Nodejs - A-quick-tour-v3
Nodejs - A-quick-tour-v3
 
Node.js
Node.jsNode.js
Node.js
 
Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)Nodejs - A quick tour (v5)
Nodejs - A quick tour (v5)
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
Node.js - As a networking tool
Node.js - As a networking toolNode.js - As a networking tool
Node.js - As a networking tool
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
Introduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCatsIntroduction to NodeJS with LOLCats
Introduction to NodeJS with LOLCats
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
Background Tasks in Node - Evan Tahler, TaskRabbit
Background Tasks in Node - Evan Tahler, TaskRabbitBackground Tasks in Node - Evan Tahler, TaskRabbit
Background Tasks in Node - Evan Tahler, TaskRabbit
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
Make BDD great again
Make BDD great againMake BDD great again
Make BDD great again
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
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
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
 

Más de Felix Geisendörfer

Más de Felix Geisendörfer (8)

Building an alarm clock with node.js
Building an alarm clock with node.jsBuilding an alarm clock with node.js
Building an alarm clock with node.js
 
How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)
 
How to Test Asynchronous Code
How to Test Asynchronous CodeHow to Test Asynchronous Code
How to Test Asynchronous Code
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?
 
Dirty - How simple is your database?
Dirty - How simple is your database?Dirty - How simple is your database?
Dirty - How simple is your database?
 
Node.js - A Quick Tour II
Node.js - A Quick Tour IINode.js - A Quick Tour II
Node.js - A Quick Tour II
 
With jQuery & CakePHP to World Domination
With jQuery & CakePHP to World DominationWith jQuery & CakePHP to World Domination
With jQuery & CakePHP to World Domination
 
ActiveDOM
ActiveDOMActiveDOM
ActiveDOM
 

Último

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
The 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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
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
 
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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 

Último (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The 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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
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...
 
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...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

Node.js - A Quick Tour

  • 1. node.js A quick tour by Felix Geisendörfer
  • 3. Why? Node's goal is to provide an easy way to build scalable network programs. -- nodejs.org
  • 4. How? Keep slow operations from blocking other operations.
  • 5. Traditional I/O var data = file.read('file.txt'); doSomethingWith(data); Something is not right here
  • 6. Traditional I/O var data = file.read('file.txt'); // zzzZZzzz FAIL! doSomethingWith(data); Don’t waste those cycles!
  • 7. Async I/O file.read('file.txt', function(data) { doSomethingWith(data); }); WIN ! doSomethingElse(); No need to wait for the disk, do something else meanwhile!
  • 9. CommonJS Modules hello.js exports.world = function() { return 'Hello World'; }; main.js var hello = require('./hello'); var sys = require('sys'); sys.puts(hello.world()); $ node main.js Hello World
  • 10. Child processes child.js var child = process.createChildProcess('sh', ['-c', 'echo hello; sleep 1; echo world;']); child.addListener('output', function (chunk) { p(chunk); }); $ node child.js "hellon" # 1 sec delay "worldn" null
  • 11. Http Server var http = require('http'); http.createServer(function(req, res) { setTimeout(function() { res.sendHeader(200, {'Content-Type': 'text/plain'}); res.sendBody('Thanks for waiting!'); res.finish(); }, 1000); }).listen(4000); $ curl localhost:4000 # 1 sec delay Thanks for waiting!
  • 12. Tcp Server var tcp = require('tcp'); tcp.createServer(function(socket) { socket.addListener('connect', function() { socket.send("Hi, How Are You?n> "); }); socket.addListener('receive', function(data) { socket.send(data); }); }).listen(4000); $ nc localhost 4000 Hi, How Are You? > Great! Great!
  • 13. DNS dns.js var dns = require('dns'); dns.resolve4('nodejs.org') .addCallback(function(r) { p(r); }); $ node dns.js [ "97.107.132.72" ]
  • 14. Watch File watch.js process.watchFile(__filename, function() { puts('You changed me!'); process.exit(); }); $ node watch.js # edit watch.js You changed me!
  • 15. ECMAScript 5 • Getters / setters var a = {}; a.__defineGetter__('foo', function() { return 'bar'; }); puts(a.foo); • Array: filter, forEach, reduce, etc. • JSON.stringify(), JSON.parse()
  • 16. There is only 1 thread file.read('file.txt', function(data) { // Will never fire }); while (true) { // this blocks the entire process } Good for conceptual simplicity Bad for CPU-bound algorithms
  • 18. Web workers • Multiple node processes that do interprocess communication • CPU-bound algorithms can run separately • Multiple CPU cores can be used efficiently
  • 19. Move C/C++ stuff to JS • Simplifies the code base • Makes contributions easier • Low-level bindings = more flexibility
  • 20. Better Socket Support • Support for unix sockets, socketpair(), pipe() • Pass sockets between processes " load balance requests between web workers • Unified socket streaming interfaces
  • 21. Even more ... • Connecting streams var f = file.writeStream('/tmp/x.txt'); connect(req.body, f); • Http parser bindings • No memcpy() for http requests + hot code reloading!
  • 22. Suitable Applications • Web frameworks • Real time • Crawlers
  • 23. More Applications • Process monitoring • File uploading • Streaming
  • 25. Http Chat in 14 LoC var http = require('http'), messages = []; http.createServer(function(req, res) { res.sendHeader(200, {'Content-Type' : 'text/plain'}); if (req.url == '/') { res.sendBody(messages.join("n")); } else if (req.url !== '/favicon.ico') { messages.push(decodeURIComponent(req.url.substr(1))); res.sendBody('ok!'); } res.finish(); }).listen(4000);
  • 26. The chat room: http://debuggable.com:4000/ Send a message: http://debuggable.com:4000/<msg>
  • 27. Questions? ✎ @felixge $ http://debuggable.com/
  • 29. Dirty NoSQL for the little man!
  • 30. Dirty JavaScript Views Memory Store Disk Persistence Speed > Safety Dirty
  • 31. Dirty Hello World hello.js var Dirty = require('../lib/dirty').Dirty, posts = new Dirty('test.dirty'); posts.add({hello: 'dirty world!'}); posts.set('my-key', {looks: 'nice'}); $ node hello.js $ cat test.dirty {"hello":"dirty world!","_key":"3b8f86..."} {"looks":"nice","_key":"my-key"}
  • 32. Reloading from Disk hello.js var Dirty = require('../lib/dirty').Dirty, posts = new Dirty('test.dirty'); posts.load() .addCallback(function() { p(posts.get('my-key')); }); $ node hello.js {"looks": "nice", "_key": "my-key"}
  • 33. Filtering records hello.js var Dirty = require('../lib/dirty').Dirty, posts = new Dirty('test.dirty'); posts.load() .addCallback(function() { var docs = posts.filter(function(doc) { return ('hello' in doc); }); p(docs); }); $ node hello.js [{"hello": "dirty world!", "_key": "3b8f86..."}]
  • 35. My Results • Set: 100k docs / sec • Iterate: 33 million docs / sec • Filter: 14 million docs / sec (on my laptop - your milage may vary)
  • 36. Use Cases • Small projects (db < memory) • Rapid prototyping • Add HTTP/TCP interface and scale
  • 37. http://github.com/felixge/node-dirty (or google for “dirty felixge”)