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

PPTX
Intro to node and mongodb 1
PPTX
Introduction to Node.js
PPTX
Introduction to Javascript By Satyen
PDF
JavaScript 101
PPTX
Lecture 5 javascript
PPT
JavaScript
PDF
From User Action to Framework Reaction
Intro to node and mongodb 1
Introduction to Node.js
Introduction to Javascript By Satyen
JavaScript 101
Lecture 5 javascript
JavaScript
From User Action to Framework Reaction

What's hot (20)

PPT
RESTful API In Node Js using Express
PDF
Node.js Explained
PDF
Introduction to Javascript programming
PDF
Introduction to Node.js Platform
PPTX
NodeJS - Server Side JS
PPTX
Introduction to JavaScript Programming
PDF
Java script tutorial
PPTX
JavaScript in Object-Oriented Way
PPTX
Nodejs functions & modules
PPTX
Javascript session 01 - Introduction to Javascript
PPT
JavaScript - An Introduction
PPTX
Introduction to node.js
PPTX
Intsllation & 1st program nodejs
PPT
Javascript Basics
PDF
Angular - Chapter 2 - TypeScript Programming
PDF
Nodejs presentation
PPTX
An Introduction to JavaScript
PDF
Node Architecture and Getting Started with Express
PDF
JavaScript guide 2020 Learn JavaScript
PDF
3rd Generation Web Application Platforms
RESTful API In Node Js using Express
Node.js Explained
Introduction to Javascript programming
Introduction to Node.js Platform
NodeJS - Server Side JS
Introduction to JavaScript Programming
Java script tutorial
JavaScript in Object-Oriented Way
Nodejs functions & modules
Javascript session 01 - Introduction to Javascript
JavaScript - An Introduction
Introduction to node.js
Intsllation & 1st program nodejs
Javascript Basics
Angular - Chapter 2 - TypeScript Programming
Nodejs presentation
An Introduction to JavaScript
Node Architecture and Getting Started with Express
JavaScript guide 2020 Learn JavaScript
3rd Generation Web Application Platforms
Ad

Viewers also liked (19)

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

Similar to Introduction to nodejs (20)

PDF
Node.js essentials
PDF
NodeJS for Beginner
PPT
Node js beginner
PPTX
Introduction to node.js GDD
PDF
540slidesofnodejsbackendhopeitworkforu.pdf
PPTX
Introduction to node.js by jiban
PPTX
NodeJs
PDF
Node.js Introduction
PPTX
Introducing Node.js in an Oracle technology environment (including hands-on)
PDF
Jaap : node, npm & grunt
PPT
Nodejs Intro Part One
PPTX
Requiring your own files.pptx
KEY
Node.js
PDF
Day In A Life Of A Node.js Developer
PDF
Day in a life of a node.js developer
ODP
Node js lecture
PPTX
Introduction to Node (15th May 2017)
PPTX
Introduction to Node.js
PPTX
Building Applications With the MEAN Stack
PPTX
Intro To Node.js
Node.js essentials
NodeJS for Beginner
Node js beginner
Introduction to node.js GDD
540slidesofnodejsbackendhopeitworkforu.pdf
Introduction to node.js by jiban
NodeJs
Node.js Introduction
Introducing Node.js in an Oracle technology environment (including hands-on)
Jaap : node, npm & grunt
Nodejs Intro Part One
Requiring your own files.pptx
Node.js
Day In A Life Of A Node.js Developer
Day in a life of a node.js developer
Node js lecture
Introduction to Node (15th May 2017)
Introduction to Node.js
Building Applications With the MEAN Stack
Intro To Node.js

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.