4. What is Node.js
ž Server Side JavaScript
ž Based on Chrome’s V8 Engines
ž Non Blocking I/O
ž 15,000+ Modules
ž Active Community (IRC, Mailing Lists, Twitter,
Github)
ž Mac, Linux and Windows (all first class
citizens)
ž One Language for Frontend and Backend
ž Node is a platform for JavaScript applications
which is not to be confused with a framework.
10. Blocking I/L
$query = 'SELECT * FROM users WHERE id = ?';
$users = query($query, array($id));
print_r($users);
$query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50';
$activities = query($query);
print_r($activities);
$query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50';
$leader_board = query($query);
11. Non-Blocking I/J
var query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [userId], function (err, results) {
console.log(results);
});
var query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50';
db.query(query, function (err, results) {
console.log(results);
});
var query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50';
db.query(query, function (err, results) {
console.log(results);
});
14. 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 )
16. Basic HTTP Server
var http = require('http');
var server = http.createServer(function (req, res) {
res.writeHead(200);
res.end('Hello World');
});
server.listen(4000);
17. Foreign Function Interface
ž node-ffi
— a Node.js addon for loading and calling
dynamic libraries using pure JavaScript. It
can be used to create bindings to native
libraries without writing any C++ code.
27. Express
ž Express is a minimal and flexible node.js
web application framework, providing a
robust set of features for building single
and multi-page, and hybrid web
applications.
35. Jade
doctype html
html(lang="en")
head
title= pageTitle
script(type='text/javascript').
if (foo) {
bar(1 + 5)
}
body
h1 Jade - node template engine
#container.col
if youAreUsingJade
p You are amazing
else
p Get on it!
p.
Jade is a terse and simple
templating language with a
strong focus on performance
and powerful features.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Jade</title>
<script type="text/javascript">
if (foo) {
bar(1 + 5)
}
</script>
</head>
<body>
<h1>Jade - node template engine</h1>
<div id="container" class="col">
<p>You are amazing</p>
<p>
Jade is a terse and simple
templating language with a
strong focus on performance
and powerful features.
</p>
</div>
</body>
</html>
36. Jade
var fn = jade.compile(jadeTemplate);
var htmlOutput = fn({
data = {'title': 'Cleaning Supplies', 'supplies': ['mop', 'broom', 'duster']}
});
h1= title
ul
each supply in supplies
li= supply
<h1>Cleaning supplies</h1>
<ul>
<li>mop</li>
<li>broom</li>
<li>duster</li>
</ul>
37. EJS
data = {'title': 'Cleaning Supplies', 'supplies': ['mop', 'broom', 'duster']}
var html = new EJS({url: 'cleaning.ejs'}).render(data);
<h1><%= title %></h1>
<ul>
<% for(var i=0; i<supplies.length;
i++) {%>
<li><%= supplies[i] %></li>
<% } %>
</ul>
<h1>Cleaning supplies</h1>
<ul>
<li>mop</li>
<li>broom</li>
<li>duster</li>
</ul>
38. Hogan.js
data = {'title': 'Cleaning Supplies', 'supplies': ['mop', 'broom', 'duster']}
var template = Hogan.compile(text);
var output = template.render(data);
<h1>{{ title }}</h1>
<ul>
{{#supplies}}
<li>{{.}}</li>
{{/supplies}}
</ul>
<h1>Cleaning supplies</h1>
<ul>
<li>mop</li>
<li>broom</li>
<li>duster</li>
</ul>
42. Mongo Driver
ž Mongoose
— Mongoose provides a straight-forward, schema-based
solution to modeling your application data and includes
built-in type casting, validation, query building,
business logic hooks and more, out of the box.
var mongoose = require('mongoose');
mongoose.connect('mongodb://192.168.68.234:27017/alex_test');
var Cat = mongoose.model('Cat', { name: String });
var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
console.log('meow');
});
44. Debugging
ž Node-inspector
— Node Inspector is a debugger interface for Node.js
applications that uses the Blink Developer Tools (formerly
WebKit Web Inspector).
— Node Inspector works in Chrome and Opera only.
$ npm install -g node-inspector
$ node-debug app.js
or
$ node-inspector &
$ node --debug app.js
45. Testing Framework
ž Mocha
— Mocha is a feature-rich JavaScript test
framework running on node.js and the
browser, making asynchronous testing
simple and fun.
ž Nodeunit
— Simple syntax, powerful tools. Nodeunit
provides easy async unit testing for node.js
and the browser.
51. Avoiding Callback Hell
ž Keep your code shallow
ž Break up your code into small
chunks(modularize)
ž Use a sequential library like async
52. async approach
ž Async is a utility module which provides
straight-forward, powerful functions for
working with asynchronous JavaScript.
$ npm install async
53. async approach
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];
});
54. promises approach
ž A tool for making and composing
asynchronous promises in JavaScript
$ npm install q
55. promises approach
var q = require('q');
var fs = require('fs');
var request = require('request');
var readFile = q.denodeify(fs.readFile);
var q_request = q.denodeify(request);
readFile('url.txt', 'utf-8')
.then(function(text) {
return q_request(text);
})
.then(function(result) {
console.log(result[0].statusCode);
})
.fail(function(err) {
console.log('an error occurs : ' + err);
});
57. generator approach
var co = require('co');
var thunkify = require('thunkify');
var request = require('request');
var get = thunkify(request.get);
co(function *(){
var a = yield get('http://google.com');
var b = yield get('http://yahoo.com');
var c = yield get('http://cloudup.com');
console.log(a[0].statusCode);
console.log(b[0].statusCode);
console.log(c[0].statusCode);
})()
co(function *(){
var a = get('http://google.com');
var b = get('http://yahoo.com');
var c = get('http://cloudup.com');
var res = yield [a, b, c];
console.log(res);
})()