2. Introduction
• Tom Hughes-Croucher
• Principal at Jetpacks for Dinosaurs
• Node.js and High-performance web site
consulting and training
• Walmart, MySpace, Joyent,Yahoo!, NASA, Tesco,
etc
• Node.js contributor
• Lead author of "Node: Up and Running"
3. Scalable Server-Side Code with JavaScript
Node Up and Running
Tom Hughes-Croucher
http://ofps.oreilly.com/titles/9781449398583/
http://shop.oreilly.com/product/0636920015956.do
13. Exercises
• Modify a basic HTTP server to return the
text "I'm learning Node"
• Change the HTTP response to HTML and
return your text in an HTML page
• Return the User-Agent string from the
browser as part of your HTML page
22. Exercise
• Create an Express server
• Make routes for ‘/’ & ‘/products’
• Serve two different pages based on
value of the query string parameter
"page"
• Create a redirect from /old to /new
• Set a cookie on the client
50. // note, io.listen() will create a http server for you
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
io.sockets.emit('this', { will: 'be received by everyone'});
socket.on('private message', function (from, msg) {
console.log('I received a private message by ', from, ' saying ',
msg);
});
socket.on('disconnect', function () {
sockets.emit('user disconnected');
});
});
51. Exercises
• Create a socket.io connect to an
express server
• Create a route which loads a page that
includes socket.io
• Send "hello world" to the client
sockets
• Make the client respond with "thanks"
and disconnect from the server
55. var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
var express = require('express')
, app = express.createServer();
var sio = require('socket.io')
, RedisStore = sio.RedisStore
, io = sio.listen(app);
app.listen(8080);
app.get('/', function(req,res) {
res.sendfile(__dirname + '/index.html');
});
// Somehow pass this information to the workers
io.set('store', new RedisStore);
// Do the work here
io.sockets.on('connection', function (socket) {
socket.on('chat', function (data) {
console.log(data);
socket.broadcast.emit('chat', data);
})
});
}
58. var http = require('http');
var req = http.request({
host: 'www.google.com',
path: '/',
port: 80,
method: 'POST'
}, function (response) {
// Do stuff with the response here
});
59. node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^ Error: Uncaught, unspecified 'error' event.
at EventEmitter.emit (events.js:47:15) at Object.<anonymous> (/
Users/you/y-u-no-listen-for-errors.js:5:9) at Module._compile
(module.js:404:26) at Object..js (module.js:410:10) at Module.load
(module.js:336:31) at Function._load (module.js:297:12) at
Array.<anonymous> (module.js:423:10) at EventEmitter._tickCallback
(node.js:126:26)
60. var http = require('http');
try {
var req = http.request({
host: 'www.google.com',
path: '/',
port: 80,
method: 'POST'
}, function (response) {
// Do stuff with the response here
});
} catch(e) {
61. var http = require('http');
var req = http.request({
host: 'www.google.com',
path: '/',
port: 80,
method: 'POST'
}, function (response) {
// Do stuff with the response here
});
req.on('error', function (err) {
//safely handle this if possible
});
64. (node) warning: possible EventEmitter memory leak detected. 11
listeners added. Use emitter.setMaxListeners() to increase limit. Trace:
at Pool.<anonymous> (events.js:101:17)
at Object.proxyRequest (~/http-proxy/lib/node-http-proxy.js:185:7)
at Server.<anonymous> (/Users/some-user/myapp.js:14:9)
at Server.emit (events.js:45:17)
at HTTPParser.onIncoming (http.js:1078:12)
at HTTPParser.onHeadersComplete (http.js:87:31)
at Socket.ondata (http.js:977:22)
at Socket._onReadable (net.js:654:27)
at IOWatcher.onReadable [as callback] (net.js:156:10)
65. var events = require('events');
function doSomethingThenTellMe () {
var emitter = new events.EventEmitter();
setTimeout(function () {
emitter.emit('done');
}, 2000);
return emitter;
}
var doingIt = doSomethingThenTellMe();
doingIt.on('done', function () {
console.log("Ok, it's done");
});
// Why are you using `.on()`?
// You only expect this event to fire once.
70. description "node.js server"
author "croucher`"
start on startup
stop on shutdown
script
# We found $HOME is needed. Without it, we ran into
problems
export HOME="/root"
exec /usr/local/bin/node /var/noderoot/index.js 2>&1 >> /
var/log/node.log
end script