SlideShare a Scribd company logo
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”)

More Related Content

KEY
Node.js - Best practices
PPTX
introduction to node.js
PPT
Node js presentation
PDF
Nodejs - A quick tour (v6)
PDF
Nodejs Explained with Examples
KEY
A million connections and beyond - Node.js at scale
PDF
Introduction to Nodejs
KEY
Writing robust Node.js applications
Node.js - Best practices
introduction to node.js
Node js presentation
Nodejs - A quick tour (v6)
Nodejs Explained with Examples
A million connections and beyond - Node.js at scale
Introduction to Nodejs
Writing robust Node.js applications

What's hot (20)

KEY
node.js: Javascript's in your backend
PDF
KEY
Introduction to node.js
PDF
Node.js in production
PDF
Non-blocking I/O, Event loops and node.js
KEY
NodeJS
PDF
Building servers with Node.js
PPT
Building your first Node app with Connect & Express
KEY
Node.js - A practical introduction (v2)
KEY
Building a real life application in node js
KEY
A language for the Internet: Why JavaScript and Node.js is right for Internet...
PPT
RESTful API In Node Js using Express
PDF
Node.js
PPTX
Java script at backend nodejs
PPTX
Node.js Patterns for Discerning Developers
PPTX
Introduction Node.js
PDF
Node.js and How JavaScript is Changing Server Programming
PDF
NodeJS for Beginner
PDF
Nodejs - A quick tour (v4)
PPTX
Intro to Node.js (v1)
node.js: Javascript's in your backend
Introduction to node.js
Node.js in production
Non-blocking I/O, Event loops and node.js
NodeJS
Building servers with Node.js
Building your first Node app with Connect & Express
Node.js - A practical introduction (v2)
Building a real life application in node js
A language for the Internet: Why JavaScript and Node.js is right for Internet...
RESTful API In Node Js using Express
Node.js
Java script at backend nodejs
Node.js Patterns for Discerning Developers
Introduction Node.js
Node.js and How JavaScript is Changing Server Programming
NodeJS for Beginner
Nodejs - A quick tour (v4)
Intro to Node.js (v1)
Ad

Viewers also liked (10)

PDF
Node.js гэж юу вэ?
PDF
Nodejs a-practical-introduction-oredev
PPTX
Create simple api using node js
PDF
Top Node.js Metrics to Watch
PDF
Getting Started with the Node.js LoopBack APi Framework
PPTX
Building a Node.js API backend with LoopBack in 5 Minutes
KEY
Getting Started with MongoDB and Node.js
PDF
Microservices with Node.js and RabbitMQ
PPTX
Introduction to Node.js
PDF
Node Foundation Membership Overview 20160907
Node.js гэж юу вэ?
Nodejs a-practical-introduction-oredev
Create simple api using node js
Top Node.js Metrics to Watch
Getting Started with the Node.js LoopBack APi Framework
Building a Node.js API backend with LoopBack in 5 Minutes
Getting Started with MongoDB and Node.js
Microservices with Node.js and RabbitMQ
Introduction to Node.js
Node Foundation Membership Overview 20160907
Ad

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

KEY
node.js dao
PDF
Nodejs - A-quick-tour-v3
KEY
Node.js
PDF
Nodejs - A quick tour (v5)
PDF
Matthew Eernisse, NodeJs, .toster {webdev}
KEY
Node.js - As a networking tool
PDF
Introduction to Node.js
KEY
Express Presentation
KEY
Introduction to NodeJS with LOLCats
PDF
Introduction to Node.js
KEY
A language for the Internet: Why JavaScript and Node.js is right for Internet...
PPTX
Building and Scaling Node.js Applications
PDF
Background Tasks in Node - Evan Tahler, TaskRabbit
PDF
Future Decoded - Node.js per sviluppatori .NET
PPTX
Make BDD great again
PDF
Node.js - async for the rest of us.
PDF
About Node.js
PPT
JS everywhere 2011
PDF
Original slides from Ryan Dahl's NodeJs intro talk
PPT
Going crazy with Node.JS and CakePHP
node.js dao
Nodejs - A-quick-tour-v3
Node.js
Nodejs - A quick tour (v5)
Matthew Eernisse, NodeJs, .toster {webdev}
Node.js - As a networking tool
Introduction to Node.js
Express Presentation
Introduction to NodeJS with LOLCats
Introduction to Node.js
A language for the Internet: Why JavaScript and Node.js is right for Internet...
Building and Scaling Node.js Applications
Background Tasks in Node - Evan Tahler, TaskRabbit
Future Decoded - Node.js per sviluppatori .NET
Make BDD great again
Node.js - async for the rest of us.
About Node.js
JS everywhere 2011
Original slides from Ryan Dahl's NodeJs intro talk
Going crazy with Node.JS and CakePHP

More from Felix Geisendörfer (8)

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

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Cloud computing and distributed systems.
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Encapsulation theory and applications.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Diabetes mellitus diagnosis method based random forest with bat algorithm
NewMind AI Weekly Chronicles - August'25 Week I
Cloud computing and distributed systems.
Digital-Transformation-Roadmap-for-Companies.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Reach Out and Touch Someone: Haptics and Empathic Computing
CIFDAQ's Market Insight: SEC Turns Pro Crypto
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Review of recent advances in non-invasive hemoglobin estimation
Building Integrated photovoltaic BIPV_UPV.pdf
Encapsulation_ Review paper, used for researhc scholars
Advanced methodologies resolving dimensionality complications for autism neur...
Spectral efficient network and resource selection model in 5G networks
MYSQL Presentation for SQL database connectivity
Encapsulation theory and applications.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...

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”)