SlideShare uma empresa Scribd logo
1 de 31
Baixar para ler offline
Node.js
Introducing
@jamescarr
It is no secret I think
Node.js is the future in
web development, and
today I will tell you
why.
Node.js is ...
Fast
Event Driven
Non-Blocking
Implemented in V8
Serverside
Awesome
(But not just for servers, more later)
Fun to code in, easy to use.
In a Nutshell
def contents = new File('foo.txt').getText()
println contents
println 'something else' All of these events
happen in sequence
Most operations in other languages are blocking
Node.js on the other hand utilizes callbacks to make operations more
asynchronous
fs.readFile('foo.txt', function(err, contents){
console.log(contents);
});
console.log('something else')
“something else” will get
executed while the file is
being read.
Code like this can allow the program to return to the event loop right away
and do other tasks.
The Traditional “Hello World” App
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello World.');
  res.end();
}).listen(80, function(){
console.log('server running on port 80');
}); /* server started */
Getting Started
http://nodejs.org
API Documentation: http://nodejs.org/api.html
IRC: irc.freenode.org #node.js
http://github.com/ry/node/wiki
Google Groups:
http://groups.google.com/group/nodejs
$ git clone http://github.com/ry/node.git
$ cd node
$ ./configure && make && sudo make install
Installation
It's really that easy given you're on linux, OSX, or cygwin
(although cygwin can sometimes be a little flakey).
Sorry, no windows support (yet).
Not too keen on using the bleeding edge?
$ git clone http://github.com/ry/node.git
$ cd node
$ ./configure && make && sudo make install
$ wget http://nodejs.org/dist/node-v0.2.4.tar.gz
$ tar zxvf node-v0.2.4.tar.gz
$ cd node
$ ./configure && make && sudo make install
The Traditional “Hello World” App
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello World.');
  res.end();
}).listen(80, function(){
console.log('server running on port 80');
}); /* server started */
Now let's
modularize this a
bit...
var http = require('http'),
greeter = require(__dirname + 'greeter');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end(greeter.greet('World');
}).listen(80, function(){
console.log('server running on port 80');
}); /* server started */
exports.greet = function (name) {
return 'Hello ' + name + '.';
}
greeter.js
In this example I've created a new module to be used from the main
script. Modularization is a major part of writing any application so let's
delve deeper into how node.js modules are constructed.
app.js
Common.js Modules
Node.js implements common.js 1.0 modules with some amount of flexibility.
Every script in node.js has a module global variable, which contains various
details about the module:
id – an identifier for this module, usually the
location on the file system
exports – an array of variables exported for
use externally. Everything else is
encapsulated within the script
parent – the module that included this
module. undefined for the top level module
99.99% of the
time
module.exports
is all you will
use.
Everything not assigned to exports (or any other node.js global objects) is
only visible within the scope of the module (Not unlike the revealing
module pattern in client
side js)
More Examples:
function sayGreeting(name) {
return 'Hello ' + name + '.';
}
exports.greet = sayGreeting;
module.exports = {
add: function(a,b){ return a+b; },
multiply: function(a,b){ return a * b}
}
Here, sayGreeting is not visible
outside of the module except
through greet.
var math = require('math'),
add = require('math').add;
math.add(2,2) == add(2,2);
More on require()
Looks in require.paths to resolve modules
Add to it:
require.paths.unshift(__dirname + '/lib');
(in case you didn't
realize, __dirname is
the dir of the current
script)Can also be called asynchronously
require('fs', function(fs){
// do something with the fs module here.
});
Exported variables can be referenced directly and even instantiated
var emitter = new(require('events').EventEmitter);
Events“Time is a sort of river of passing events, and strong is its current; no sooner is a thing
brought to sight than it is swept by and another takes its place, and this too will be
swept away.”
- Marcus Aurelius
EventEmitter
allows the firing and listening
of events within node.js.
Objects that allow
attachment of event
listeners use EventEmitter
under the hood.
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
emitter.on('pricechange', function(old, new){
console.log(old + ' changed to ' + new);
});
emitter.emit('pricechange', 12.99, 10.99);
emitter.emit('pricechange', 15.99, 17.99);
In Action
Keep In Mind...
Event emitters don't interact with each other
var events = new(require('events').EventEmitter);
var events2 = new(require('events').EventEmitter);
events2.on('test', function(msg){
console.log(msg);
});
events.on('test', function(msg){
console.log(msg);
});
events.emit('test', 'some message');
Here the events2 callback will never get
called. That is because the callback is
assigned to a different EventEmitter
instance.
EventEmitter is best used “mixed in” with an object to let clients
respond to different events that happen
var EventEmitter = require('events').EventEmitter;
function User(name){
this.name = name
}
// This is one of many ways to inherit from another object
User.prototype.__proto__ = EventEmitter.prototype
var user = new User('Jim');
user.on('login', function(){
console.log('user ' + this.name + ' has logged in');
});
user.emit('login');
Events are really a great way to let clients use your module
and respond to different events it might fire without having
to be too concerned about the details.
Let's take a turn back towards modules.
Sure, creating a module is easy, but how
can you share modules with others?
Or take advantage of existing
modules?
NPMNode
Package
Manager
Ruby has gem to install manage packages, node.js has npm
Install: https://github.com/isaacs/npm
http://npmjs.org
Simple install: curl http://npmjs.org/install.sh | sh
Browse packages: http://npm.mape.me
In addition to being a kick ass package management system it also makes
it very easy to bundle dependencies with a project for deployment.
npm bundle ./vendor
Some of my Favorite
Modules
Express.js
Get it: npm install express
Very simple and elegant routing syntax for building applications
Supports a variety of template engines out of the box: jade, haml.js, ejs.
http://expressjs.com
Commandline tool (express) to quickly create a skeletal project structure
var express = require('express'),
app = express.createServer();
app.get('/users', function(req, res){
res.render('users.jade', {
locals:{
users:[];
}
});
});
app.get('/user/:id', function(req, res){
res.send('user ' + req.params.id);
});
app.listen(3000);
Express.js
Connect.js
Middleware for building web applications and more specifically web
application frameworks. Think of it as a framework's framework. ;)
(for example, express uses connect under the hood)
Need sessions, json-rpc, routing? Connect is for you!
https://github.com/senchalabs/connect
npm install connect
Connect addons: oauth, openid, etc
WebSockets
WebSockets have a lot of popularity in node.js due to the early adoption and ease of use
Two real contenders: websocket-server and socket.io
Websocket-server – implements the specs
Socket.IO – uses it's own non-spec API on top of websockets, but works with all sorts of
fallback mechanisms using a client side library
http://socket.io
https://github.com/miksago/node-websocket-server
npm install websocket-server
npm install socket.io
WebWorkers
Implements the WebWorkers API as a mechanism for interprocess
communication
Start up a script in a separate process, send and receive messages to it
https://github.com/pgriess/node-webworker
https://github.com/cramforce/node-worker
WebWorkers
Demo: Finding Perfect Numbers
Clustering
The answer: node.js doesn't have any built in support for clustering
However, there is much work afoot that will help depending on your needs.
node-event-stream - https://github.com/miksago/node-
eventstream
Uses websockets to replicated events between servers
node-amqp-events –
uses amqp to replicate events between servers
There also many modules for storing sessions in various NoSQL databases
to make them appear replicated across server instances
Warning
API is subject to change
In fact examples
you find online are
probably outdated.
The channel and
mailing list can
help.
Questions?

Mais conteúdo relacionado

Mais procurados

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
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js ExplainedJeff Kunkle
 
Introduction to Javascript programming
Introduction to Javascript programmingIntroduction to Javascript programming
Introduction to Javascript programmingFulvio Corno
 
Introduction to Node.js Platform
Introduction to Node.js PlatformIntroduction to Node.js Platform
Introduction to Node.js PlatformNaresh Chintalcheru
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS Ganesh Kondal
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript ProgrammingRaveendra R
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorialDoeun KOCH
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayChamnap Chhorn
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modulesmonikadeshmane
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptLivingston Samuel
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsDinesh U
 
Intsllation & 1st program nodejs
Intsllation & 1st program nodejsIntsllation & 1st program nodejs
Intsllation & 1st program nodejsmonikadeshmane
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming WebStackAcademy
 
An Introduction to JavaScript
An Introduction to JavaScriptAn Introduction to JavaScript
An Introduction to JavaScripttonyh1
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptLaurence Svekis ✔
 
3rd Generation Web Application Platforms
3rd Generation Web Application Platforms3rd Generation Web Application Platforms
3rd Generation Web Application PlatformsNaresh Chintalcheru
 

Mais procurados (20)

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 Explained
Node.js ExplainedNode.js Explained
Node.js Explained
 
Introduction to Javascript programming
Introduction to Javascript programmingIntroduction to Javascript programming
Introduction to Javascript programming
 
Introduction to Node.js Platform
Introduction to Node.js PlatformIntroduction to Node.js Platform
Introduction to Node.js Platform
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript Programming
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Intsllation & 1st program nodejs
Intsllation & 1st program nodejsIntsllation & 1st program nodejs
Intsllation & 1st program nodejs
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
An Introduction to JavaScript
An Introduction to JavaScriptAn Introduction to JavaScript
An Introduction to JavaScript
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
 
3rd Generation Web Application Platforms
3rd Generation Web Application Platforms3rd Generation Web Application Platforms
3rd Generation Web Application Platforms
 

Destaque

Codesria Conference on Electronic Publishing 2016
Codesria Conference on Electronic Publishing 2016 Codesria Conference on Electronic Publishing 2016
Codesria Conference on Electronic Publishing 2016 Eve Gray
 
Publishing Development Research and Adding Value
Publishing Development Research and Adding ValuePublishing Development Research and Adding Value
Publishing Development Research and Adding ValueEve Gray
 
Palm internationalreport 201000922
Palm internationalreport 201000922Palm internationalreport 201000922
Palm internationalreport 201000922Eve Gray
 
Dealing in Disruption - OA policy in an African context
Dealing in Disruption - OA policy in an African contextDealing in Disruption - OA policy in an African context
Dealing in Disruption - OA policy in an African contextEve Gray
 
OA and the Decolonization of the university in Africa 2016
OA and the Decolonization of the university in Africa 2016 OA and the Decolonization of the university in Africa 2016
OA and the Decolonization of the university in Africa 2016 Eve Gray
 
Policy overview unam 120522
Policy overview unam 120522Policy overview unam 120522
Policy overview unam 120522Eve Gray
 
Intro to Node.js
Intro to Node.jsIntro to Node.js
Intro to Node.jsJames Carr
 
Open Access Week 2009 University of the Western Cape
Open Access Week 2009 University of the Western CapeOpen Access Week 2009 University of the Western Cape
Open Access Week 2009 University of the Western CapeEve Gray
 
Open Access in 2012 – a developing country perspective
Open Access in 2012 – a developing country perspectiveOpen Access in 2012 – a developing country perspective
Open Access in 2012 – a developing country perspectiveEve Gray
 
The Changing Journal Landscape
The Changing Journal Landscape The Changing Journal Landscape
The Changing Journal Landscape Eve Gray
 
Contextualizing Policy Developments in Open Knowledge in South Africa
Contextualizing  Policy Developments in Open  Knowledge in South AfricaContextualizing  Policy Developments in Open  Knowledge in South Africa
Contextualizing Policy Developments in Open Knowledge in South AfricaEve Gray
 
Scholarly Publishing in Africa - Namibia
Scholarly Publishing in Africa - NamibiaScholarly Publishing in Africa - Namibia
Scholarly Publishing in Africa - NamibiaEve Gray
 
OA 2013 - A Broader Vision of Open Access for Development
OA 2013 - A Broader Vision of Open Access for Development OA 2013 - A Broader Vision of Open Access for Development
OA 2013 - A Broader Vision of Open Access for Development Eve Gray
 
High powered messaging with RabbitMQ
High powered messaging with RabbitMQHigh powered messaging with RabbitMQ
High powered messaging with RabbitMQJames Carr
 

Destaque (19)

Codesria Conference on Electronic Publishing 2016
Codesria Conference on Electronic Publishing 2016 Codesria Conference on Electronic Publishing 2016
Codesria Conference on Electronic Publishing 2016
 
Think
ThinkThink
Think
 
Publishing Development Research and Adding Value
Publishing Development Research and Adding ValuePublishing Development Research and Adding Value
Publishing Development Research and Adding Value
 
Palm internationalreport 201000922
Palm internationalreport 201000922Palm internationalreport 201000922
Palm internationalreport 201000922
 
Dealing in Disruption - OA policy in an African context
Dealing in Disruption - OA policy in an African contextDealing in Disruption - OA policy in an African context
Dealing in Disruption - OA policy in an African context
 
OA and the Decolonization of the university in Africa 2016
OA and the Decolonization of the university in Africa 2016 OA and the Decolonization of the university in Africa 2016
OA and the Decolonization of the university in Africa 2016
 
Policy overview unam 120522
Policy overview unam 120522Policy overview unam 120522
Policy overview unam 120522
 
Intro to Node.js
Intro to Node.jsIntro to Node.js
Intro to Node.js
 
Open Access Week 2009 University of the Western Cape
Open Access Week 2009 University of the Western CapeOpen Access Week 2009 University of the Western Cape
Open Access Week 2009 University of the Western Cape
 
Rom
RomRom
Rom
 
Portfolio Sculptures 2007
Portfolio Sculptures 2007Portfolio Sculptures 2007
Portfolio Sculptures 2007
 
Wsp Deck Games
Wsp Deck GamesWsp Deck Games
Wsp Deck Games
 
Open Access in 2012 – a developing country perspective
Open Access in 2012 – a developing country perspectiveOpen Access in 2012 – a developing country perspective
Open Access in 2012 – a developing country perspective
 
The Changing Journal Landscape
The Changing Journal Landscape The Changing Journal Landscape
The Changing Journal Landscape
 
Contextualizing Policy Developments in Open Knowledge in South Africa
Contextualizing  Policy Developments in Open  Knowledge in South AfricaContextualizing  Policy Developments in Open  Knowledge in South Africa
Contextualizing Policy Developments in Open Knowledge in South Africa
 
Scholarly Publishing in Africa - Namibia
Scholarly Publishing in Africa - NamibiaScholarly Publishing in Africa - Namibia
Scholarly Publishing in Africa - Namibia
 
OA 2013 - A Broader Vision of Open Access for Development
OA 2013 - A Broader Vision of Open Access for Development OA 2013 - A Broader Vision of Open Access for Development
OA 2013 - A Broader Vision of Open Access for Development
 
Mockito
MockitoMockito
Mockito
 
High powered messaging with RabbitMQ
High powered messaging with RabbitMQHigh powered messaging with RabbitMQ
High powered messaging with RabbitMQ
 

Semelhante a Introduction to nodejs

Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event EmittersTheCreativedev Blog
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdfSudhanshiBakre1
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDDSudar Muthu
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comVan-Duyet Le
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsSebastian Springer
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
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
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS MultithreadingRicha Jain
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS ExpressDavid Boyer
 

Semelhante a Introduction to nodejs (20)

Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
Node js beginner
Node js beginnerNode js beginner
Node js beginner
 
Book
BookBook
Book
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdf
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
NodeJS
NodeJSNodeJS
NodeJS
 
Express node js
Express node jsExpress node js
Express node js
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
 
Divide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.jsDivide and Conquer – Microservices with Node.js
Divide and Conquer – Microservices with Node.js
 
Node js
Node jsNode js
Node js
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
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.
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 

Introduction to nodejs

  • 2. It is no secret I think Node.js is the future in web development, and today I will tell you why.
  • 3. Node.js is ... Fast Event Driven Non-Blocking Implemented in V8 Serverside Awesome (But not just for servers, more later) Fun to code in, easy to use.
  • 5. def contents = new File('foo.txt').getText() println contents println 'something else' All of these events happen in sequence Most operations in other languages are blocking
  • 6. Node.js on the other hand utilizes callbacks to make operations more asynchronous fs.readFile('foo.txt', function(err, contents){ console.log(contents); }); console.log('something else') “something else” will get executed while the file is being read. Code like this can allow the program to return to the event loop right away and do other tasks.
  • 7. The Traditional “Hello World” App var http = require('http'); http.createServer(function (req, res) {   res.writeHead(200, {'Content-Type': 'text/plain'});   res.write('Hello World.');   res.end(); }).listen(80, function(){ console.log('server running on port 80'); }); /* server started */
  • 8. Getting Started http://nodejs.org API Documentation: http://nodejs.org/api.html IRC: irc.freenode.org #node.js http://github.com/ry/node/wiki Google Groups: http://groups.google.com/group/nodejs
  • 9. $ git clone http://github.com/ry/node.git $ cd node $ ./configure && make && sudo make install Installation It's really that easy given you're on linux, OSX, or cygwin (although cygwin can sometimes be a little flakey). Sorry, no windows support (yet). Not too keen on using the bleeding edge? $ git clone http://github.com/ry/node.git $ cd node $ ./configure && make && sudo make install $ wget http://nodejs.org/dist/node-v0.2.4.tar.gz $ tar zxvf node-v0.2.4.tar.gz $ cd node $ ./configure && make && sudo make install
  • 10. The Traditional “Hello World” App var http = require('http'); http.createServer(function (req, res) {   res.writeHead(200, {'Content-Type': 'text/plain'});   res.write('Hello World.');   res.end(); }).listen(80, function(){ console.log('server running on port 80'); }); /* server started */ Now let's modularize this a bit...
  • 11. var http = require('http'), greeter = require(__dirname + 'greeter'); http.createServer(function (req, res) {   res.writeHead(200, {'Content-Type': 'text/plain'});   res.end(greeter.greet('World'); }).listen(80, function(){ console.log('server running on port 80'); }); /* server started */ exports.greet = function (name) { return 'Hello ' + name + '.'; } greeter.js In this example I've created a new module to be used from the main script. Modularization is a major part of writing any application so let's delve deeper into how node.js modules are constructed. app.js
  • 12. Common.js Modules Node.js implements common.js 1.0 modules with some amount of flexibility. Every script in node.js has a module global variable, which contains various details about the module: id – an identifier for this module, usually the location on the file system exports – an array of variables exported for use externally. Everything else is encapsulated within the script parent – the module that included this module. undefined for the top level module 99.99% of the time module.exports is all you will use.
  • 13. Everything not assigned to exports (or any other node.js global objects) is only visible within the scope of the module (Not unlike the revealing module pattern in client side js) More Examples: function sayGreeting(name) { return 'Hello ' + name + '.'; } exports.greet = sayGreeting; module.exports = { add: function(a,b){ return a+b; }, multiply: function(a,b){ return a * b} } Here, sayGreeting is not visible outside of the module except through greet. var math = require('math'), add = require('math').add; math.add(2,2) == add(2,2);
  • 14. More on require() Looks in require.paths to resolve modules Add to it: require.paths.unshift(__dirname + '/lib'); (in case you didn't realize, __dirname is the dir of the current script)Can also be called asynchronously require('fs', function(fs){ // do something with the fs module here. }); Exported variables can be referenced directly and even instantiated var emitter = new(require('events').EventEmitter);
  • 15. Events“Time is a sort of river of passing events, and strong is its current; no sooner is a thing brought to sight than it is swept by and another takes its place, and this too will be swept away.” - Marcus Aurelius
  • 16. EventEmitter allows the firing and listening of events within node.js. Objects that allow attachment of event listeners use EventEmitter under the hood.
  • 17. var EventEmitter = require('events').EventEmitter; var emitter = new EventEmitter(); emitter.on('pricechange', function(old, new){ console.log(old + ' changed to ' + new); }); emitter.emit('pricechange', 12.99, 10.99); emitter.emit('pricechange', 15.99, 17.99); In Action
  • 18. Keep In Mind... Event emitters don't interact with each other var events = new(require('events').EventEmitter); var events2 = new(require('events').EventEmitter); events2.on('test', function(msg){ console.log(msg); }); events.on('test', function(msg){ console.log(msg); }); events.emit('test', 'some message'); Here the events2 callback will never get called. That is because the callback is assigned to a different EventEmitter instance.
  • 19. EventEmitter is best used “mixed in” with an object to let clients respond to different events that happen var EventEmitter = require('events').EventEmitter; function User(name){ this.name = name } // This is one of many ways to inherit from another object User.prototype.__proto__ = EventEmitter.prototype var user = new User('Jim'); user.on('login', function(){ console.log('user ' + this.name + ' has logged in'); }); user.emit('login');
  • 20. Events are really a great way to let clients use your module and respond to different events it might fire without having to be too concerned about the details. Let's take a turn back towards modules. Sure, creating a module is easy, but how can you share modules with others? Or take advantage of existing modules?
  • 21. NPMNode Package Manager Ruby has gem to install manage packages, node.js has npm Install: https://github.com/isaacs/npm http://npmjs.org Simple install: curl http://npmjs.org/install.sh | sh Browse packages: http://npm.mape.me In addition to being a kick ass package management system it also makes it very easy to bundle dependencies with a project for deployment. npm bundle ./vendor
  • 22. Some of my Favorite Modules
  • 23. Express.js Get it: npm install express Very simple and elegant routing syntax for building applications Supports a variety of template engines out of the box: jade, haml.js, ejs. http://expressjs.com Commandline tool (express) to quickly create a skeletal project structure
  • 24. var express = require('express'), app = express.createServer(); app.get('/users', function(req, res){ res.render('users.jade', { locals:{ users:[]; } }); }); app.get('/user/:id', function(req, res){ res.send('user ' + req.params.id); }); app.listen(3000); Express.js
  • 25. Connect.js Middleware for building web applications and more specifically web application frameworks. Think of it as a framework's framework. ;) (for example, express uses connect under the hood) Need sessions, json-rpc, routing? Connect is for you! https://github.com/senchalabs/connect npm install connect Connect addons: oauth, openid, etc
  • 26. WebSockets WebSockets have a lot of popularity in node.js due to the early adoption and ease of use Two real contenders: websocket-server and socket.io Websocket-server – implements the specs Socket.IO – uses it's own non-spec API on top of websockets, but works with all sorts of fallback mechanisms using a client side library http://socket.io https://github.com/miksago/node-websocket-server npm install websocket-server npm install socket.io
  • 27. WebWorkers Implements the WebWorkers API as a mechanism for interprocess communication Start up a script in a separate process, send and receive messages to it https://github.com/pgriess/node-webworker https://github.com/cramforce/node-worker
  • 29. Clustering The answer: node.js doesn't have any built in support for clustering However, there is much work afoot that will help depending on your needs. node-event-stream - https://github.com/miksago/node- eventstream Uses websockets to replicated events between servers node-amqp-events – uses amqp to replicate events between servers There also many modules for storing sessions in various NoSQL databases to make them appear replicated across server instances
  • 30. Warning API is subject to change In fact examples you find online are probably outdated. The channel and mailing list can help.