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

More Related Content

What's hot (20)

PPT
RESTful API In Node Js using Express
Jeetendra singh
 
PDF
Node.js Explained
Jeff Kunkle
 
PDF
Introduction to Javascript programming
Fulvio Corno
 
PDF
Introduction to Node.js Platform
Naresh Chintalcheru
 
PPTX
NodeJS - Server Side JS
Ganesh Kondal
 
PPTX
Introduction to JavaScript Programming
Raveendra R
 
PDF
Java script tutorial
Doeun KOCH
 
PPTX
JavaScript in Object-Oriented Way
Chamnap Chhorn
 
PPTX
Nodejs functions & modules
monikadeshmane
 
PPTX
Javascript session 01 - Introduction to Javascript
Livingston Samuel
 
PPT
JavaScript - An Introduction
Manvendra Singh
 
PPTX
Introduction to node.js
Dinesh U
 
PPTX
Intsllation & 1st program nodejs
monikadeshmane
 
PPT
Javascript Basics
Vishal Mittal
 
PDF
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
PDF
Nodejs presentation
Arvind Devaraj
 
PPTX
An Introduction to JavaScript
tonyh1
 
PDF
Node Architecture and Getting Started with Express
jguerrero999
 
PDF
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
PDF
3rd Generation Web Application Platforms
Naresh Chintalcheru
 
RESTful API In Node Js using Express
Jeetendra singh
 
Node.js Explained
Jeff Kunkle
 
Introduction to Javascript programming
Fulvio Corno
 
Introduction to Node.js Platform
Naresh Chintalcheru
 
NodeJS - Server Side JS
Ganesh Kondal
 
Introduction to JavaScript Programming
Raveendra R
 
Java script tutorial
Doeun KOCH
 
JavaScript in Object-Oriented Way
Chamnap Chhorn
 
Nodejs functions & modules
monikadeshmane
 
Javascript session 01 - Introduction to Javascript
Livingston Samuel
 
JavaScript - An Introduction
Manvendra Singh
 
Introduction to node.js
Dinesh U
 
Intsllation & 1st program nodejs
monikadeshmane
 
Javascript Basics
Vishal Mittal
 
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
Nodejs presentation
Arvind Devaraj
 
An Introduction to JavaScript
tonyh1
 
Node Architecture and Getting Started with Express
jguerrero999
 
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
3rd Generation Web Application Platforms
Naresh Chintalcheru
 

Viewers also liked (19)

PPTX
Codesria Conference on Electronic Publishing 2016
Eve Gray
 
PPS
Think
Singlaji Deepak
 
PDF
Publishing Development Research and Adding Value
Eve Gray
 
PDF
Palm internationalreport 201000922
Eve Gray
 
PPT
Dealing in Disruption - OA policy in an African context
Eve Gray
 
PPTX
OA and the Decolonization of the university in Africa 2016
Eve Gray
 
PPTX
Policy overview unam 120522
Eve Gray
 
PPT
Intro to Node.js
James Carr
 
PPT
Open Access Week 2009 University of the Western Cape
Eve Gray
 
PDF
Rom
ronong
 
PDF
Portfolio Sculptures 2007
MichaelFargarden
 
PDF
Wsp Deck Games
dcampbell48
 
PPTX
Open Access in 2012 – a developing country perspective
Eve Gray
 
PPTX
The Changing Journal Landscape
Eve Gray
 
PPTX
Contextualizing Policy Developments in Open Knowledge in South Africa
Eve Gray
 
PPT
Scholarly Publishing in Africa - Namibia
Eve Gray
 
PPTX
OA 2013 - A Broader Vision of Open Access for Development
Eve Gray
 
PPT
Mockito
James Carr
 
PPTX
High powered messaging with RabbitMQ
James Carr
 
Codesria Conference on Electronic Publishing 2016
Eve Gray
 
Publishing Development Research and Adding Value
Eve Gray
 
Palm internationalreport 201000922
Eve Gray
 
Dealing in Disruption - OA policy in an African context
Eve Gray
 
OA and the Decolonization of the university in Africa 2016
Eve Gray
 
Policy overview unam 120522
Eve Gray
 
Intro to Node.js
James Carr
 
Open Access Week 2009 University of the Western Cape
Eve Gray
 
Rom
ronong
 
Portfolio Sculptures 2007
MichaelFargarden
 
Wsp Deck Games
dcampbell48
 
Open Access in 2012 – a developing country perspective
Eve Gray
 
The Changing Journal Landscape
Eve Gray
 
Contextualizing Policy Developments in Open Knowledge in South Africa
Eve Gray
 
Scholarly Publishing in Africa - Namibia
Eve Gray
 
OA 2013 - A Broader Vision of Open Access for Development
Eve Gray
 
Mockito
James Carr
 
High powered messaging with RabbitMQ
James Carr
 
Ad

Similar to Introduction to nodejs (20)

PDF
Build Web Apps using Node.js
davidchubbs
 
PDF
soft-shake.ch - Hands on Node.js
soft-shake.ch
 
PPTX
Introduction to Node.js
Vikash Singh
 
PPT
Node js Modules and Event Emitters
TheCreativedev Blog
 
PPT
Node js beginner
Sureshreddy Nalimela
 
PDF
Book
luis_lmro
 
KEY
Writing robust Node.js applications
Tom Croucher
 
PDF
Global objects in Node.pdf
SudhanshiBakre1
 
PPTX
Introduction to node.js GDD
Sudar Muthu
 
PPTX
NodeJS
Alok Guha
 
PDF
Express node js
Yashprit Singh
 
ODP
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
PPTX
node.js.pptx
rani marri
 
PDF
Divide and Conquer – Microservices with Node.js
Sebastian Springer
 
PDF
Node js
Rohan Chandane
 
PDF
NodeJS for Beginner
Apaichon Punopas
 
PPTX
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva
 
PDF
Node.js - async for the rest of us.
Mike Brevoort
 
PPT
iOS Multithreading
Richa Jain
 
PDF
All aboard the NodeJS Express
David Boyer
 
Build Web Apps using Node.js
davidchubbs
 
soft-shake.ch - Hands on Node.js
soft-shake.ch
 
Introduction to Node.js
Vikash Singh
 
Node js Modules and Event Emitters
TheCreativedev Blog
 
Node js beginner
Sureshreddy Nalimela
 
Book
luis_lmro
 
Writing robust Node.js applications
Tom Croucher
 
Global objects in Node.pdf
SudhanshiBakre1
 
Introduction to node.js GDD
Sudar Muthu
 
NodeJS
Alok Guha
 
Express node js
Yashprit Singh
 
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
node.js.pptx
rani marri
 
Divide and Conquer – Microservices with Node.js
Sebastian Springer
 
NodeJS for Beginner
Apaichon Punopas
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Ricardo Silva
 
Node.js - async for the rest of us.
Mike Brevoort
 
iOS Multithreading
Richa Jain
 
All aboard the NodeJS Express
David Boyer
 
Ad

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.