An Introduction to Node.js

James M. Greene
** Title used with permission from Max Ogden

Node is...

# Starts a Node REPLnode# Runs a single command with Nodenode -e "console.log('Node Process ID: ' + process.pid);"# Run a particular script with Nodenode my_app.js
// Import the "fs" (file system) module from Node.js corevar fs = require('fs');// Import the "async" module from Node.js userland // (after running `npm install async`)var async = require('async');// Import a module relative to the app/module you're working onvar awesomeUtil = require('./util/awesome');
module.exports = function() {// A utility method or constructor};
module.exports = {// An "API" object};
// Contents of "util/awesome.js"module.exports = { awesome: function() { console.log("AWESOME!"); } };
// Contents of "app.js"var awesomeUtil = require("./util/awesome");awesomeUtil.awesome();
# Install a dependency globally npm install -g grunt-cli# Scaffold your new Node module/app (mainly "package.json") npm init# Install a "dev" dependency locally and update "package.json"npm install --save-dev grunt# Publish a new module of your own to NPM npm publish
# Scaffold your new Node module (mainly "package.json")npm init# Code your module up! Tweak "package.json" as you go.# Share it with the worldnpm publish
// app.js
process.on("exit", function() {
console.log("Exiting... asynchronous flow");
});
process.nextTick(function() {
console.log("Next tick, asynchronous flow");
});
console.log("Synchronous flow");
# Results
$> node app.js
Synchronous flow
Next tick, asynchronous flow
Exiting... asynchronous flow

step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
});Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
// Do something with value4
})
.catch(function (error) {
// Handle any error from all above steps
})
.done();async.waterfall([
function (callback) {
callback(null, 'one', 'two');
},
function (arg1, arg2, callback) {
callback(null, 'three');
},
function (arg1, callback) {
// arg1 now equals 'three'
callback(null, 'done');
}
], function (err, result) {
// result now equals 'done'
}); // EventTarget interfacesdocument.addEventListener("DOMContentReady", handlerFn, false);// jQuery events$(".priamry-btn").on("click", handlerFn);// Unhandled exception handlers (sort of)window.onerror = function(msg, file, line, col, err) {return true;};
// Global eventsprocess.on("exit", function() {console.log("Exiting...");});// Individual objects' eventssocketClient.on("connect", handlerFn);
// Create your own Emittersfunction MyClass() {}var util = require('util');var EventEmitter = require('events').EventEmitter;util.inherits(MyClass, EventEmitter);var instance = new MyClass();instance.on("ping", function(e) {instance.emit("pong");});instance.on("pong", function(e) {console.log("Ping! Pong!");});instance.emit("ping");
range.on("preheat", function() {
pot.on("boil", function() {
rice.on("cooked", function() {
dinner.serve(rice);
});
});
}); var http = require('http');
var fs = require('fs');
var path = require('path');
var server = http.createServer(
function (req, res) {
var file = path.join(__dirname, 'data.txt');
// BUFFERING BUFFERING BUFFERING...
fs.readFile(file, function (err, data) {
res.end(data);
});
}
);
server.listen(8000);
var http = require('http');
var fs = require('fs');
var path = require('path');
var server = http.createServer(
function (req, res) {
var file = path.join(__dirname, 'data.txt');
// Open a readable stream
var stream = fs.createReadStream(file);
// Stream chunks of bytes as they come
stream.pipe(res);
}
);
server.listen(8000);
# Installnpm install -g node-inspector# Runnode-debug -p 8181 app.js