Top Banner
node.js A quick tour by Felix Geisendörfer 1 Donnerstag, 4. März 2010
47

Node.js - A Quick Tour II

Jan 15, 2015

Download

Technology

Updated version of the talk for 0.1.30+
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Node.js - A Quick Tour II

node.jsA quick tour

by Felix Geisendörfer1Donnerstag, 4. März 2010

Page 2: Node.js - A Quick Tour II

Who is talking?

• node.js hacker

• Cofounder of Debuggable

• CakePHP core alumnus

2Donnerstag, 4. März 2010

Page 3: Node.js - A Quick Tour II

Why Node?

3Donnerstag, 4. März 2010

Page 4: Node.js - A Quick Tour II

Why?

Node's goal is to provide an easy way to build scalable network programs.

-- nodejs.org

4Donnerstag, 4. März 2010

Page 5: Node.js - A Quick Tour II

How?

Keep slow operations from blocking other operations.

5Donnerstag, 4. März 2010

Page 6: Node.js - A Quick Tour II

Traditional I/O

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

Something is not right here

6Donnerstag, 4. März 2010

Page 7: Node.js - A Quick Tour II

Traditional I/O

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

// zzzZZzzz

doSomethingWith(data);

Don’t waste those cycles!

FAIL!

7Donnerstag, 4. März 2010

Page 8: Node.js - A Quick Tour II

Async I/O

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

doSomethingElse();

WIN ✔

No need to wait for the disk, do something else meanwhile!

8Donnerstag, 4. März 2010

Page 9: Node.js - A Quick Tour II

The Present

9Donnerstag, 4. März 2010

Page 10: Node.js - A Quick Tour II

Quality components

• V8 (developed for google chrome)

• libev (event loop)

• libeio (non-block posix, thread pool)

10Donnerstag, 4. März 2010

Page 11: Node.js - A Quick Tour II

CommonJS Modules

exports.world = function() { return 'Hello World';};

hello.js

main.js

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

$ node main.jsHello World

11Donnerstag, 4. März 2010

Page 12: Node.js - A Quick Tour II

Child processes

var child = process.createChildProcess('sh',['-c', 'echo hello; sleep 1; echo world;']);child.addListener('data', function (chunk) { p(chunk);});

$ node child.js "hello\n"# 1 sec delay"world\n"null

child.js

12Donnerstag, 4. März 2010

Page 13: Node.js - A Quick Tour II

Http Server

var http = require('http');http.createServer(function(req, res) { setTimeout(function() { res.writeHeader(200, {'Content-Type': 'text/plain'}); res.write('Thanks for waiting!'); res.close(); }, 1000);}).listen(4000);

$ curl localhost:4000# 1 sec delayThanks for waiting!

13Donnerstag, 4. März 2010

Page 14: Node.js - A Quick Tour II

Tcp Servervar tcp = require('tcp');tcp.createServer(function(socket) { socket.addListener('connect', function() { socket.write("Hi, How Are You?\n> "); }); socket.addListener('data', function(data) { socket.write(data); });}).listen(4000);

$ nc localhost 4000Hi, How Are You?> Great!Great!

14Donnerstag, 4. März 2010

Page 15: Node.js - A Quick Tour II

DNS

var dns = require('dns');dns.resolve4('nodejs.org', function(err, addr, ttl, cname) { p(addr, ttl, cname);});

dns.js

$ node dns.js[ '97.107.132.72' ]84279'nodejs.org'

15Donnerstag, 4. März 2010

Page 16: Node.js - A Quick Tour II

Watch File

process.watchFile(__filename, function() { puts('You changed me!'); process.exit();});

watch.js

$ node watch.js# edit watch.jsYou changed me!

16Donnerstag, 4. März 2010

Page 17: Node.js - A Quick Tour II

ECMAScript 5

• Getters / settersvar a = {};a.__defineGetter__('foo', function() { return 'bar';});puts(a.foo);

• Array: filter, forEach, reduce, etc.

• JSON.stringify(), JSON.parse()& more [1]

17Donnerstag, 4. März 2010

Page 18: Node.js - A Quick Tour II

There is only 1 thread

file.read('file.txt', function(data) { // Will never fire});

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

Good for conceptual simplicityBad for CPU-bound algorithms

18Donnerstag, 4. März 2010

Page 19: Node.js - A Quick Tour II

The Future

19Donnerstag, 4. März 2010

Page 20: Node.js - A Quick Tour II

Web workers

• Multiple node processes that do interprocess communication

• CPU-bound algorithms can run separately

• Multiple CPU cores can be used efficiently

20Donnerstag, 4. März 2010

Page 21: Node.js - A Quick Tour II

Streams

see [2]

• Node is working towards a unified data stream interface

• Stream can be readable, writable or both

21Donnerstag, 4. März 2010

Page 22: Node.js - A Quick Tour II

Readable Streams

• events: ‘data’, ‘end’

• methods: pause(), resume()

22Donnerstag, 4. März 2010

Page 23: Node.js - A Quick Tour II

Writeable Streams

• events: ‘drain’, ‘close’

• methods: write(), close()

23Donnerstag, 4. März 2010

Page 24: Node.js - A Quick Tour II

Stream Redirection

http.createServer(function (req, res) { // Open writable file system var temp = fs.openTemporaryFile(); // Pump the request into the temp file. stream.pump(req, temp, function (err) { if (err) throw err;

p('sweet!'); });});

24Donnerstag, 4. März 2010

Page 25: Node.js - A Quick Tour II

Better Socket Support

• Support for unix sockets, socketpair(), pipe()

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

25Donnerstag, 4. März 2010

Page 26: Node.js - A Quick Tour II

Debugger

• V8 support debugging

• Node has a few bugs with exposing the debugger, those need fixing

• Command line node-debug REPL tool

26Donnerstag, 4. März 2010

Page 27: Node.js - A Quick Tour II

Readline and Curses

• Bindings for JavaScript

• Would allow to build better command line tools

• Goal should be to write a screen clone in node

27Donnerstag, 4. März 2010

Page 28: Node.js - A Quick Tour II

HTML and XML parsing

• HTML is a major protocol

• Node should be able to parse dirty XML/HTML

• Should be a SAX-style parser in pure JS

28Donnerstag, 4. März 2010

Page 29: Node.js - A Quick Tour II

Support for Windows

• Patches welcome! : )

29Donnerstag, 4. März 2010

Page 30: Node.js - A Quick Tour II

Hot code reloading

• Reload module during runtime

• Update code without taking server offline

(maybe)

30Donnerstag, 4. März 2010

Page 31: Node.js - A Quick Tour II

Suitable Applications

• Web frameworks

• Real time

• Crawlers

31Donnerstag, 4. März 2010

Page 32: Node.js - A Quick Tour II

More Applications

• Process monitoring

• File uploading

• Streaming

32Donnerstag, 4. März 2010

Page 33: Node.js - A Quick Tour II

Let’s write a chat

33Donnerstag, 4. März 2010

Page 34: Node.js - A Quick Tour II

Http Chat in 14 LoCvar http = require('http'), messages = [];

http.createServer(function(req, res) { res.writeHeader(200, {'Content-Type' : 'text/plain'}); if (req.url == '/') { res.write(messages.join("\n")); } else if (req.url !== '/favicon.ico') { messages.push(decodeURIComponent(req.url.substr(1))); res.write('ok!'); } res.close();}).listen(4000);

34Donnerstag, 4. März 2010

Page 35: Node.js - A Quick Tour II

Production ready?

• For small systems, yes.

• Perfect example: Comet server

• Usually few bugs, but API is still changing

35Donnerstag, 4. März 2010

Page 36: Node.js - A Quick Tour II

Questions?

☝@felixge

http://debuggable.com/$✎

36Donnerstag, 4. März 2010

Page 38: Node.js - A Quick Tour II

Bonus Slides!

38Donnerstag, 4. März 2010

Page 39: Node.js - A Quick Tour II

Dirty

Dirty

JavaScript ViewsDisk Persistence

Memory StoreSpeed > Safety

39Donnerstag, 4. März 2010

Page 40: Node.js - A Quick Tour II

A scriptable key-value store

• Let your business logic and your data share the same memory / process

• Network = OVERHEAD - Avoid whenever possible

• V8 makes it very fast

40Donnerstag, 4. März 2010

Page 41: Node.js - A Quick Tour II

How fast?

• Set: 3-5 million docs / sec

• Get: 40-50 million docs / sec

(on my laptop - your milage may vary)41Donnerstag, 4. März 2010

Page 42: Node.js - A Quick Tour II

Benchmarks

Do your own!

42Donnerstag, 4. März 2010

Page 43: Node.js - A Quick Tour II

Disk persistence

• Append-only log

• Writes happen every x-Sec or every x-Records

• Callbacks fire after disk write succeeded

43Donnerstag, 4. März 2010

Page 44: Node.js - A Quick Tour II

Dirty Hello World

$ node hello.js$ cat test.dirty {"hello":"dirty world!","_key":"3b8f86..."}{"looks":"nice","_key":"my-key"}

var Dirty = require('dirty').Dirty, posts = new Dirty('test.dirty');

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

hello.js

44Donnerstag, 4. März 2010

Page 45: Node.js - A Quick Tour II

Reloading from Disk

var Dirty = require('dirty').Dirty, posts = new Dirty('test.dirty');

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

$ node hello.js{"looks": "nice", "_key": "my-key"}

hello.js

45Donnerstag, 4. März 2010

Page 46: Node.js - A Quick Tour II

Use Cases

• Small projects (db < memory)

• Rapid prototyping

• Add HTTP/TCP interface and scale

46Donnerstag, 4. März 2010

Page 47: Node.js - A Quick Tour II

http://github.com/felixge/node-dirty

(or google for “dirty felixge”)

47Donnerstag, 4. März 2010