SlideShare a Scribd company logo
Intro to Node.js
        Chris Cowan
            Lead Engineer
    http://www.plus3network.com
Node’s Goal is to provide an
 easy way to build scalable
    network programs.
Node.js is NOT another
  web framework!

  But you can create a web framework using NPM modules.
Node.js is…
             Web Server
              TCP Server
     Awesome Robot Controller
     Command Line Application
            Proxy Server
          Streaming Server
          VoiceMail Server
           Music Machine
Anything that has to deal with high I/O
Node.js is
Server Side JavaScript!
Node.js is

FUN!
Why Node.js?
• Non Blocking I/O
• Based on Chrome’s V8 Engines (FAST!)
• 15,000+ Modules
• Active Community (IRC, Mailing
  Lists, Twitter, Github)
• Mac, Linux and Windows (all first class citizens)
• One Language for Frontend and Backend
• JavaScript is the Language of the Web
Installing Node.js
Mac OS X
1. Go to http://nodejs.org and click install
2. Install the downloaded package

Windows
1. Go to http://nodejs.org and click install
2. Install the downloaded package

Linux (and *nix variants)
1. Go to http://nodejs.org and click install
2. Decompress source and… ./configure … make … make install
   ( for Ubuntu use Chris Lea’s PPA – ppa:chris-lea/node.js )
Some Basic
 Examples
Hello World
Create hello-world.js
console.log(‘Hello World’);

On the command line run
node hello-world.js

You should see
Hello World
Basic HTTP Server
var http = require('http');

var server = http.createServer(function (req, res) {
  res.writeHead(200);
  res.end('Hello World');
});

server.listen(4000);



                   *Running this script my development box,
                   I can achieve 10,000+ requests per second
                        with 100 concurrent connections
                            without breaking a sweat
Some people use the
 core http module to
build their web apps,
most use a framework
     like Express
 or Connect or Flatiron or Tako or Derby or Geddy or Mojito or …
Visit
http://expressjs.com/guide.html
       for a detailed guide
         on using Express
What is Non-Blocking I/O?
    And why should I care?
Blocking I/
// Get User – 20ms
$query = 'SELECT * FROM users WHERE id = ?';
$users = query($query, array($id));
print_r($users);

// Get Activities – 100ms
$query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50';
$activities = query($query);
print_r($activities);

// Get Leader Board – 150ms
$query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50';
$leader_board = query($query);




          270ms = SUM(user, activities, leaderboard)
Non-Blocking I/
// Get User – 20ms
var query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [userId], function (err, results) {
  console.log(results);
});

// Get Activities – 100ms
var query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50';
db.query(query, function (err, results) {
  console.log(results);
});

// Get Leader Board – 150ms
var query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50';
db.query(query, function (err, results) {
  console.log(results);
});




           150ms = MAX(user, activities, leaderboard)
The most jarring thing
about Server Side JavaScript
  is thinking in callbacks
The Node Callback Pattern
awesomeFunction(arg, function (err, data) {
   if (err) {
      // Handle Error
   }
   // Do something awesome with results.
});

• Error first then success… ALWAYS!
• Because this is the de-facto standard 99.99999% of the time
  you will be able to guess how a Node library will work.
Callbacks are the Devil’s Work!
                          Don’t go down this rabbit hole…
var userQuery = 'SELECT * FROM users WHERE id = ?';
var activityQuery = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50';
var leaderBoardQuery = 'SELECT count(points) as total, user_id FROM activities LIMIT 50';

db.query(userQuery, [id], function (userErr, userResults) {
 db.query(activityQuery, function (activityErr, activityResults) {
    db.query(leaderBoardQuery, function (leaderBoardErr, leaderBoardResults) {

        // Do something here

      });
   });
});


   One of the biggest mistakes is to get yourself in
    to callback hell by nesting callbacks inside of
          callbacks inside of more callbacks.
Avoiding Callback Hell
• Keep your code shallow
• Break up your code into small chunks
• Use a sequential library like async
• Visit http://callbackhell.com
Async to the rescue!
var async = require('async');
var db = require(’db');

function getUser (callback) {
  var query = 'SELECT * FROM users WHERE id = ?';
  db.query(query, [userId], callback);
}

function getActivities (callback) {
  var query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50';
  db.query(query, callback);
}

function getLeaderBoard (callback) {
  var query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50';
  db.query(query, callback);
}

var tasks = [getUser, getActivities, getLeaderBoard];
async.parallel(tasks, function (err, results) {
  var user       = results[0][0];
  var activities = results[1];
  var leaderBoard = results[2];
});
Async provides several useful
 patterns for asynchronous control
            flow including:
 parallel, series, waterfall, auto and
                queue.
                      Visit
        https://github.com/caolan/async
for a detailed guide on using the async module.
The Node Package Manager
 otherwise know as… NPM

 It’s how you harness the
    awesomeness of the
    Node.js community!
Using NPM
It’s standard practice to install modules locally for your current project.
Modules are installed in the ./node_modules in the current directory.

To Install a new module

npm install <module>

To find a module in the NPM repository

npm search <search string>

To list the modules (and their dependencies) in the current project

npm list

To see module details

npm info <module>
DON’T INSTALL
MODULES GLOBALLY!
 Unless they are tools like node-dev, jake, express, minify-js
  OR linked development modules but more on that later.
NPM is awesome sauce!

               Visit
        https://npmjs.org
for more details about NPM and to
browse the current NPM Repository
Creating your own modules
• Node.js uses CommonJS Modules
• require(‘./example’) will load either
  example.js or example/index.js or the entry
  point specified in package.json
• Run npm init to bootstrap your new module
• Try to stick to creating Pure JavaScript
  modules if possible. It will give you less
  headaches down the road.
Basic Module Example
Everything exposed via module.exports is available as an instance variable.

var currentCount = 0;

module.exports.incr = function () {
  return ++currentCount;
};

Once you’ve created a module in counter.js you use it like this…
var counter = require(’./counter');
var count = counter.incr();

Keep this in mind… modules are loaded once and cached. So when
you load the module a second time in your app, require just
returns the cache copied. This lets you do interesting things…
Installing your module
• Run npm link in the module working directory
• Then run npm link <module> in the your project
  folder to link it from the global module to your
  local node_modules.

• OR you can create a private registry
  (See https://npmjs.org/doc/registry.html)

• OR just link it by hand :P
My Favorite Modules
• request      • jake
• async        • hogan.js
• node-dev     • connect
• underscore   • moment
• express      • mysql
Questions?
Contact me at chris@chriscowan.us

More Related Content

What's hot (20)

PPTX
Introduction to Node js
Akshay Mathur
 
PDF
All aboard the NodeJS Express
David Boyer
 
PPTX
Nodejs intro
Ndjido Ardo BAR
 
PDF
Node.js and How JavaScript is Changing Server Programming
Tom Croucher
 
KEY
Writing robust Node.js applications
Tom Croucher
 
PPTX
Java script at backend nodejs
Amit Thakkar
 
KEY
OSCON 2011 - Node.js Tutorial
Tom Croucher
 
PDF
Node ppt
Tamil Selvan R S
 
PPTX
Node js introduction
Joseph de Castelnau
 
PDF
Node Architecture and Getting Started with Express
jguerrero999
 
PPT
Node js presentation
martincabrera
 
PDF
Use Node.js to create a REST API
Fabien Vauchelles
 
PPT
RESTful API In Node Js using Express
Jeetendra singh
 
PPTX
NodeJS - Server Side JS
Ganesh Kondal
 
PDF
Nodejs in Production
William Bruno Moraes
 
KEY
node.js: Javascript's in your backend
David Padbury
 
PDF
Building servers with Node.js
ConFoo
 
PDF
Non-blocking I/O, Event loops and node.js
Marcus Frödin
 
PDF
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
PDF
Node.js Explained
Jeff Kunkle
 
Introduction to Node js
Akshay Mathur
 
All aboard the NodeJS Express
David Boyer
 
Nodejs intro
Ndjido Ardo BAR
 
Node.js and How JavaScript is Changing Server Programming
Tom Croucher
 
Writing robust Node.js applications
Tom Croucher
 
Java script at backend nodejs
Amit Thakkar
 
OSCON 2011 - Node.js Tutorial
Tom Croucher
 
Node js introduction
Joseph de Castelnau
 
Node Architecture and Getting Started with Express
jguerrero999
 
Node js presentation
martincabrera
 
Use Node.js to create a REST API
Fabien Vauchelles
 
RESTful API In Node Js using Express
Jeetendra singh
 
NodeJS - Server Side JS
Ganesh Kondal
 
Nodejs in Production
William Bruno Moraes
 
node.js: Javascript's in your backend
David Padbury
 
Building servers with Node.js
ConFoo
 
Non-blocking I/O, Event loops and node.js
Marcus Frödin
 
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
Node.js Explained
Jeff Kunkle
 

Viewers also liked (20)

PPSX
Node.js In The Enterprise - A Primer
Naveen S.R
 
PDF
Node.js in action
Simon Su
 
PDF
#7 "Многообещающий JavaScript – Promises" Денис Речкунов
JSib
 
PPTX
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
Calvin Tan
 
PDF
Migrating a Monolithic App to Microservices on Cloud Foundry
Tony Erwin
 
PPTX
Microservices and modern backends - Azure Meetup Frankfurt
Damir Dobric
 
PPTX
A High-Performance Solution To Microservices UI Composition
Alexey Gravanov
 
PPTX
Building a Web Frontend with Microservices and NGINX Plus
NGINX, Inc.
 
PDF
Node.js & Twitter Bootstrap Crash Course
Aaron Silverman
 
PDF
Building microservices web application using scala & akka
Binh Nguyen
 
PDF
Burgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
Dimitar Danailov
 
PDF
Introduction to Node.js: perspectives from a Drupal dev
mcantelon
 
PDF
Webconf nodejs-production-architecture
Ben Lin
 
PDF
Introduction to node js - From "hello world" to deploying on azure
Colin Mackay
 
PDF
Building Scalable Web Applications Using Microservices Architecture and NodeJ...
NodejsFoundation
 
PPTX
An Unexpected Solution to Microservices UI Composition
Dr. Arif Wider
 
PDF
Complete MVC on NodeJS
Hüseyin BABAL
 
PPT
Nodejs Event Driven Concurrency for Web Applications
Ganesh Iyer
 
PPTX
Create Rest API in Nodejs
Irfan Maulana
 
PDF
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
Node.js In The Enterprise - A Primer
Naveen S.R
 
Node.js in action
Simon Su
 
#7 "Многообещающий JavaScript – Promises" Денис Речкунов
JSib
 
Why Node, Express and Postgres - presented 23 Feb 15, Talkjs, Microsoft Audit...
Calvin Tan
 
Migrating a Monolithic App to Microservices on Cloud Foundry
Tony Erwin
 
Microservices and modern backends - Azure Meetup Frankfurt
Damir Dobric
 
A High-Performance Solution To Microservices UI Composition
Alexey Gravanov
 
Building a Web Frontend with Microservices and NGINX Plus
NGINX, Inc.
 
Node.js & Twitter Bootstrap Crash Course
Aaron Silverman
 
Building microservices web application using scala & akka
Binh Nguyen
 
Burgas Conf 21.06.2014 - Single page application Angularjs and Nodejs
Dimitar Danailov
 
Introduction to Node.js: perspectives from a Drupal dev
mcantelon
 
Webconf nodejs-production-architecture
Ben Lin
 
Introduction to node js - From "hello world" to deploying on azure
Colin Mackay
 
Building Scalable Web Applications Using Microservices Architecture and NodeJ...
NodejsFoundation
 
An Unexpected Solution to Microservices UI Composition
Dr. Arif Wider
 
Complete MVC on NodeJS
Hüseyin BABAL
 
Nodejs Event Driven Concurrency for Web Applications
Ganesh Iyer
 
Create Rest API in Nodejs
Irfan Maulana
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
Ad

Similar to Intro To Node.js (20)

PPTX
Intro to node and mongodb 1
Mohammad Qureshi
 
PPTX
Intro to Node.js (v1)
Chris Cowan
 
PDF
An introduction to Node.js
Kasey McCurdy
 
ODP
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
PPTX
Nodejs
Vinod Kumar Marupu
 
PPTX
Node js Introduction
sanskriti agarwal
 
PPTX
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
KEY
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
DOCX
unit 2 of Full stack web development subject
JeneferAlan1
 
PPTX
Building Applications With the MEAN Stack
Nir Noy
 
PDF
Node.js Course 1 of 2 - Introduction and first steps
Manuel Eusebio de Paz Carmona
 
PPTX
Introduction to node.js GDD
Sudar Muthu
 
PPTX
An overview of node.js
valuebound
 
PPTX
NodeJS guide for beginners
Enoch Joshua
 
PDF
Download full ebook of Learning Node Shelley Powers instant download pdf
zeitsloyerqy
 
PPT
Node js
Chirag Parmar
 
PDF
Node.js - async for the rest of us.
Mike Brevoort
 
KEY
Practical Use of MongoDB for Node.js
async_io
 
PPTX
NodeJS
Alok Guha
 
PPTX
A complete guide to Node.js
Prabin Silwal
 
Intro to node and mongodb 1
Mohammad Qureshi
 
Intro to Node.js (v1)
Chris Cowan
 
An introduction to Node.js
Kasey McCurdy
 
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
Node js Introduction
sanskriti agarwal
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
unit 2 of Full stack web development subject
JeneferAlan1
 
Building Applications With the MEAN Stack
Nir Noy
 
Node.js Course 1 of 2 - Introduction and first steps
Manuel Eusebio de Paz Carmona
 
Introduction to node.js GDD
Sudar Muthu
 
An overview of node.js
valuebound
 
NodeJS guide for beginners
Enoch Joshua
 
Download full ebook of Learning Node Shelley Powers instant download pdf
zeitsloyerqy
 
Node js
Chirag Parmar
 
Node.js - async for the rest of us.
Mike Brevoort
 
Practical Use of MongoDB for Node.js
async_io
 
NodeJS
Alok Guha
 
A complete guide to Node.js
Prabin Silwal
 
Ad

Recently uploaded (20)

PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
July Patch Tuesday
Ivanti
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
July Patch Tuesday
Ivanti
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 

Intro To Node.js

  • 1. Intro to Node.js Chris Cowan Lead Engineer http://www.plus3network.com
  • 2. Node’s Goal is to provide an easy way to build scalable network programs.
  • 3. Node.js is NOT another web framework! But you can create a web framework using NPM modules.
  • 4. Node.js is… Web Server TCP Server Awesome Robot Controller Command Line Application Proxy Server Streaming Server VoiceMail Server Music Machine Anything that has to deal with high I/O
  • 7. Why Node.js? • Non Blocking I/O • Based on Chrome’s V8 Engines (FAST!) • 15,000+ Modules • Active Community (IRC, Mailing Lists, Twitter, Github) • Mac, Linux and Windows (all first class citizens) • One Language for Frontend and Backend • JavaScript is the Language of the Web
  • 8. Installing Node.js Mac OS X 1. Go to http://nodejs.org and click install 2. Install the downloaded package Windows 1. Go to http://nodejs.org and click install 2. Install the downloaded package Linux (and *nix variants) 1. Go to http://nodejs.org and click install 2. Decompress source and… ./configure … make … make install ( for Ubuntu use Chris Lea’s PPA – ppa:chris-lea/node.js )
  • 10. Hello World Create hello-world.js console.log(‘Hello World’); On the command line run node hello-world.js You should see Hello World
  • 11. Basic HTTP Server var http = require('http'); var server = http.createServer(function (req, res) { res.writeHead(200); res.end('Hello World'); }); server.listen(4000); *Running this script my development box, I can achieve 10,000+ requests per second with 100 concurrent connections without breaking a sweat
  • 12. Some people use the core http module to build their web apps, most use a framework like Express or Connect or Flatiron or Tako or Derby or Geddy or Mojito or …
  • 14. What is Non-Blocking I/O? And why should I care?
  • 15. Blocking I/ // Get User – 20ms $query = 'SELECT * FROM users WHERE id = ?'; $users = query($query, array($id)); print_r($users); // Get Activities – 100ms $query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50'; $activities = query($query); print_r($activities); // Get Leader Board – 150ms $query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50'; $leader_board = query($query); 270ms = SUM(user, activities, leaderboard)
  • 16. Non-Blocking I/ // Get User – 20ms var query = 'SELECT * FROM users WHERE id = ?'; db.query(query, [userId], function (err, results) { console.log(results); }); // Get Activities – 100ms var query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50'; db.query(query, function (err, results) { console.log(results); }); // Get Leader Board – 150ms var query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50'; db.query(query, function (err, results) { console.log(results); }); 150ms = MAX(user, activities, leaderboard)
  • 17. The most jarring thing about Server Side JavaScript is thinking in callbacks
  • 18. The Node Callback Pattern awesomeFunction(arg, function (err, data) { if (err) { // Handle Error } // Do something awesome with results. }); • Error first then success… ALWAYS! • Because this is the de-facto standard 99.99999% of the time you will be able to guess how a Node library will work.
  • 19. Callbacks are the Devil’s Work! Don’t go down this rabbit hole… var userQuery = 'SELECT * FROM users WHERE id = ?'; var activityQuery = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50'; var leaderBoardQuery = 'SELECT count(points) as total, user_id FROM activities LIMIT 50'; db.query(userQuery, [id], function (userErr, userResults) { db.query(activityQuery, function (activityErr, activityResults) { db.query(leaderBoardQuery, function (leaderBoardErr, leaderBoardResults) { // Do something here }); }); }); One of the biggest mistakes is to get yourself in to callback hell by nesting callbacks inside of callbacks inside of more callbacks.
  • 20. Avoiding Callback Hell • Keep your code shallow • Break up your code into small chunks • Use a sequential library like async • Visit http://callbackhell.com
  • 21. Async to the rescue! var async = require('async'); var db = require(’db'); function getUser (callback) { var query = 'SELECT * FROM users WHERE id = ?'; db.query(query, [userId], callback); } function getActivities (callback) { var query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50'; db.query(query, callback); } function getLeaderBoard (callback) { var query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50'; db.query(query, callback); } var tasks = [getUser, getActivities, getLeaderBoard]; async.parallel(tasks, function (err, results) { var user = results[0][0]; var activities = results[1]; var leaderBoard = results[2]; });
  • 22. Async provides several useful patterns for asynchronous control flow including: parallel, series, waterfall, auto and queue. Visit https://github.com/caolan/async for a detailed guide on using the async module.
  • 23. The Node Package Manager otherwise know as… NPM It’s how you harness the awesomeness of the Node.js community!
  • 24. Using NPM It’s standard practice to install modules locally for your current project. Modules are installed in the ./node_modules in the current directory. To Install a new module npm install <module> To find a module in the NPM repository npm search <search string> To list the modules (and their dependencies) in the current project npm list To see module details npm info <module>
  • 25. DON’T INSTALL MODULES GLOBALLY! Unless they are tools like node-dev, jake, express, minify-js OR linked development modules but more on that later.
  • 26. NPM is awesome sauce! Visit https://npmjs.org for more details about NPM and to browse the current NPM Repository
  • 27. Creating your own modules • Node.js uses CommonJS Modules • require(‘./example’) will load either example.js or example/index.js or the entry point specified in package.json • Run npm init to bootstrap your new module • Try to stick to creating Pure JavaScript modules if possible. It will give you less headaches down the road.
  • 28. Basic Module Example Everything exposed via module.exports is available as an instance variable. var currentCount = 0; module.exports.incr = function () { return ++currentCount; }; Once you’ve created a module in counter.js you use it like this… var counter = require(’./counter'); var count = counter.incr(); Keep this in mind… modules are loaded once and cached. So when you load the module a second time in your app, require just returns the cache copied. This lets you do interesting things…
  • 29. Installing your module • Run npm link in the module working directory • Then run npm link <module> in the your project folder to link it from the global module to your local node_modules. • OR you can create a private registry (See https://npmjs.org/doc/registry.html) • OR just link it by hand :P
  • 30. My Favorite Modules • request • jake • async • hogan.js • node-dev • connect • underscore • moment • express • mysql