introduction to node.js: what, why and how?

21
Introduction to Node.js: What, why and how? Christian Joudrey - @cjoudrey

Upload: christian-joudrey

Post on 10-May-2015

3.181 views

Category:

Technology


0 download

DESCRIPTION

Talk given at NodeMTL #1

TRANSCRIPT

Page 1: Introduction to Node.js: What, why and how?

Introduction to Node.js:What, why and how?

Christian Joudrey - @cjoudrey

Page 2: Introduction to Node.js: What, why and how?

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

Page 3: Introduction to Node.js: What, why and how?

What is node?

• Command line tool to run JavaScript:$ node my_app.js

• Built on top of Google's V8 JavaScript engine

• Provides a JavaScript API for network and file system

• Event-based, non-blocking I/O APIs

Page 4: Introduction to Node.js: What, why and how?

my_app.js:

setTimeout(function () { console.log('world'); }, 2000);

console.log('hello');

Running it:

$ node my_app.js hello world

Page 5: Introduction to Node.js: What, why and how?

The cost of I/O?

• Accessing RAM ~ 250 CPU cycles

• Disk operations ~ 41 000 000 CPU cycleso Reading a fileo Writing to a file

• Network I/O ~ 240 000 000 CPU cycleso Database query responseso Http responseso Memcache results

Page 6: Introduction to Node.js: What, why and how?

• I/O is expensive

• Most web applications are I/O bound, not CPU bound

Page 7: Introduction to Node.js: What, why and how?

Handling I/O

• Apache is multithreaded (depending on conf.)o Spawns a thread per request (or process)

• Each request is in its own "box", blocking I/O is "okay".

result = query('SELECT * FROM ...');print result.id;

Page 8: Introduction to Node.js: What, why and how?

Thread-per-connection is expensive

http://blog.webfaction.com/a-little-holiday-present

Page 9: Introduction to Node.js: What, why and how?

• nginx uses an event-loop, like node.

Page 10: Introduction to Node.js: What, why and how?

Enter node...

• Single thread for your code

• ...but, I/O runs in parallel

• Handle thousands of concurrent connections with a single process

• Need to be very careful with CPU-intensive code

Page 11: Introduction to Node.js: What, why and how?

I/O in node

• No function should directly perform I/O.

• To receive info from disk, network, or another process there must be a callback.

• Callbacks are typically in the format:function (err, result) { }

query('SELECT * FROM ...', function (err, result){ if (!err) { print result.id; }});

Page 12: Introduction to Node.js: What, why and how?

CommonJS Module System

mymodule.js: module.exports.add = function (a, b) { return a + b;};

Using the module: var mymodule = require('mymodule');console.log(mymodule.add(5, 2));

Page 13: Introduction to Node.js: What, why and how?

Built-in Modules

• File Systemrequire('fs');

• HTTP Client and Serverrequire('http');

• TCP Socketsrequire('net');

• Many more: http://nodejs.org/docs/v0.4.8/api/

Page 14: Introduction to Node.js: What, why and how?

Getting Started

• Node.js: http://nodejs.org/#download

• Build instructions: http://bit.ly/egLfzuMac: brew update && brew install node

• npm, a package manager for Node:curl http://npmjs.org/install.sh | sh

• Many modules at: http://search.npmjs.org/

• Windows support isn't great (for the moment)

Page 15: Introduction to Node.js: What, why and how?

Reading a JSON Filevar fs = require('fs');var file = __dirname + '/test.json';

fs.readFile(file, 'utf8', function (err, data) { if (err) { console.log('Error: ' + err); return; }

data = JSON.parse(data);

console.dir(data);});

https://gist.github.com/988107

Page 16: Introduction to Node.js: What, why and how?

Simple HTTP Server

var http = require('http');

var s = http.createServer(function (req, res) { var headers = {'Content-Type': 'text/html'}; req.writeHead(200, headers); res.end('<h1>hello world</h1>');});

s.listen(8080, '127.0.0.1');

https://gist.github.com/988108

Page 17: Introduction to Node.js: What, why and how?

Express makes HTTP easier

• Node's HTTP module is low level.

• Express is a simple framework inspired by Sinatra (Ruby).

• Installing Express:npm install express && npm install jade

• Robust verb-based routingo app.get('/about', function(req, res) { });o app.post('/login', function(req, res) { });

• Templating (with Jade or EJS)

• Sessions

Page 18: Introduction to Node.js: What, why and how?

Getting Started with Express

• Generate skeleton apps:express –help

• Generate app with sessions and template engine:express --sessions --template jade hello/

• Generated structure:$ ls hello/app.js logs pids public test views

$ ls hello/views/index.jade layout.jade

Page 19: Introduction to Node.js: What, why and how?

Useful Modules

• Express - Sinatra-like Web Frameworkhttp://expressjs.comnpm install express

• Jade - HAML-like Template Enginehttp://jade-lang.comnpm install jade

• Socket.IO - Cross-browser WebSocket libraryhttp://socket.io/npm install socket.io

Page 20: Introduction to Node.js: What, why and how?

Interesting Links

• Lots of Express examples: http://bit.ly/ExpressExamples

• Express Documentation: http://bit.ly/ExpressDocs

• NodeMTL.com Source Code: http://bit.ly/iZCjod

• Database wrappers and ORMs:

o Mongoose (MongoDB, ORM-like): https://github.com/LearnBoost/mongoose

o Couch-ar (CouchDB, Active Record implementation):https://github.com/scottburch/couch-ar

Page 21: Introduction to Node.js: What, why and how?

Questions? :)