SlideShare a Scribd company logo
1 of 65
Download to read offline
Agenda
ž  Introduction
ž  Package Manager
ž  Web Framework
ž  Testing
ž  Callback Hell
ž  Obfuscator
ž  Build Tool
Introduction
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.
What is Node.js
Who's using Node.js
Who's using Node.js
Why Node.js
ž  Apache v.s. Nginx
Why Node.js
ž  Apache v.s. Nginx
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);
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);
});
Why Node.js
Why Node.js
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 )
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);
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.
Package Manager
NPM
ž  Simple CLI tools
ž  Register registry.npmjs.org
ž  Web site npmjs.org
ž  Included in node.js since 0.6
ž  Git friendly
NPM Usage
ž  npm search express
ž  npm info express
ž  npm install -g express
ž  npm update
ž  npm publish
NPM Usage
ž  npm install ./package.tgz
ž  npm install sax --save
ž  npm install node-tap --save-dev
ž  npm install dtrace-provider --save-optional
ž  npm install https://github.com/indexzero/forever/
tarball/v0.5.6
Module Metas
ž  package.json
{
"name": "my-website",
"version": "0.0.1",
"dependencies": {
"express": "2.4.7",
"jade": ">= 0.0.1",
"oauth": ">= 0.9.5"
}
}
Transitive dependencies
Virtual Environment
ž  nvm (starred 3884 on github)
—  Simple bash script to manage multiple active
node.js versions
$ nvm install 0.10.29
$ nvm ls
v0.10.29
current: v0.10.29
$ nvm use 0.10.29
Now using node v0.10.29
$ node --version
v0.10.29
Virtual Environment
ž  nave (starred 645 on github)
—  Virtual Environments for Node
—  run on various node.js builds
$ nave install latest
$ nave ls
src:
0.10.28 0.11.13
installed:
0.10.28 0.11.13
$ nave use 0.11.13
Already installed: 0.11.13
using 0.11.13
$ node --version
v0.11.13
Web Framework
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.
Express
ž  Generate an app
$ npm install -g express-generator
$ express --css stylus myapp
create : myapp
create : myapp/package.json
create : myapp/app.js
create : myapp/public
create : myapp/public/javascripts
create : myapp/public/images
create : myapp/routes
create : myapp/routes/index.js
create : myapp/routes/users.js
create : myapp/public/stylesheets
create : myapp/public/stylesheets/style.styl
create : myapp/views
create : myapp/views/index.jade
create : myapp/views/layout.jade
create : myapp/views/error.jade
create : myapp/bin
create : myapp/bin/www
install dependencies:
$ cd myapp && npm install
run the app:
$ DEBUG=myapp ./bin/www
Express Middleware
ž  Middleware is any number of functions
that are invoked by the Express.js
routing layer before your final request
handler is
Express Middleware
var app = express();
app.use(function(req, res, next) {
console.log('%s %s', req.method, req.url);
next();
});
app.get('/', function(req, res, next) {
res.send('Hello World!');
});
app.get('/help', function(req, res, next) {
res.send('Nope.. nothing to see here');
});
Express Middleware
ž  body-parser
—  body
—  co-body
—  raw-body
ž  compression
ž  connect-timeout
ž  cookie-parser
ž  cookie-session
ž  csurf
ž  errorhandler
ž  express-session
ž  method-override
ž  morgan
ž  response-time
ž  serve-favicon
ž  serve-index
ž  serve-static
ž  vhost
Express I18N
app.js
var i18n = require('i18n');
app.use(i18n.init);
app.use(function (req, res, next) {
res.locals.__ = function () {
return function (text, render) {
return i18n.__.apply(req, arguments);
};
};
next();
});
en.js
{
"Home": "Home",
"About Us": "About Us",
"Program": "Program",
"Venue": "Venue",
"Sponsors": "Sponsors"
}
menu.hjs
<li>{{#__}}Home{{/__}}</li>
<li>{{#__}}About Us{{/__}}</li>
<li>{{#__}}Program{{/__}}</li>
<li>{{#__}}Venue{{/__}}</li>
<li>{{#__}}Sponsors{{/__}}</li>
menu.html
<li>Home</li>
<li>About Us</li>
<li>Program</li>
<li>Venue</li>
<li>Sponsors</li>
Express Authentication
ž  Passport
—  authentication middleware for Node.js.
app.post('/login',
passport.authenticate('local'),
function(req, res) {
res.redirect('/users/' + req.user.username);
});
app.use(function(req, res, next) {
if (!req.session.userid) {
return res.redirect(url);
}
next();
});
Template Engine
ž  Jade
ž  EJS
ž  Hogan.js
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>
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>
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>
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>
Redis Driver
$ npm install redis hiredis
var redis = require("redis"),
client = redis.createClient();
// if you'd like to select database 3, instead of 0 (default), call
// client.select(3, function() { /* ... */ });
client.on("error", function (err) {
console.log("Error " + err);
});
client.set("string key", "string val", redis.print);
client.hset("hash key", "hashtest 1", "some value", redis.print);
client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
client.hkeys("hash key", function (err, replies) {
console.log(replies.length + " replies:");
replies.forEach(function (reply, i) {
console.log(" " + i + ": " + reply);
});
client.quit();
});
Redis Sentinel Driver
$ npm install redis hiredis redis-sentinel
var sentinel = require('redis-sentinel');
var endpoints = [
{host: '127.0.0.1', port: 26379},
{host: '127.0.0.1', port: 26380}
];
var opts = {};
var masterName = 'mymaster';
var redisClient = sentinel.createClient(endpoints, masterName, opts);
Mongo Driver
$ npm install mongodb
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://192.168.68.234:27017/qcloud',
function(err, db) {
if(err) throw err;
var collection = db.collection('device');
collection.find({'device_name':'alexnas'}).toArray(function(err, results)
{
console.dir(results);
db.close();
});
});
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');
});
Testing
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
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.
Mocha
var assert = require("assert");
describe('Test', function() {
var foo;
beforeEach(function() {
console.log('setup');
foo = 'bar';
});
afterEach(function() {
console.log('teardown');
});
it('#test1', function() {
console.log('run test1');
assert.equal(foo, 'bar');
});
});
Nodeunit
module.exports = {
setUp: function (callback) {
console.log('setup');
this.foo = 'bar';
callback();
},
tearDown: function (callback) {
console.log('teardown');
callback();
},
test1: function (test) {
console.log('run test1');
test.equals(this.foo, 'bar');
test.done();
}
};
Callback Hell
Callback Hell
doAsync1(function() {
doAsync2(function() {
doAsync3(function() {
doAsync4(function() {
});
});
});
});
Callback Hell
ž  An example from http://callbackhell.com/
fs.readdir(source, function(err, files) {
if (err) {
console.log('Error finding files: ' + err)
} else {
files.forEach(function(filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function(err, values) {
if (err) {
console.log('Error identifying file size: ' + err)
} else {
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach( function(width, widthIndex) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(destination + 'w' + width + '_' + filename, function(err) {
if (err)
console.log('Error writing file: ' + err)
})
}.bind(this))
}
})
})
}
})
Avoiding Callback Hell
ž  Keep your code shallow
ž  Break up your code into small
chunks(modularize)
ž  Use a sequential library like async
async approach
ž  Async is a utility module which provides
straight-forward, powerful functions for
working with asynchronous JavaScript.
$ npm install async
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];
});
promises approach
ž  A tool for making and composing
asynchronous promises in JavaScript
$ npm install q
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);
});
generator approach
ž  Generators are lightweight co-routines
for JavaScript.
ž  Available in Node >=0.11.2 or above
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);
})()
Obfuscator
Obfuscator
ž  YUI Compressor
ž  Google Closure Compiler
ž  minifyjs
ž  uglify-js
uglifyjs app.js -m -o app-min.js
ž  node-obfuscator
obfuscator --entry app.js app.js routes/index.js routes/user.js
Obfuscator
ž  Write your extension
—  Implement encrypt/decrypt functions
require.extensions[".jse"] = function (m) {
m.exports = MyNativeExtension.decrypt(fs.readFileSync(m.filename));
};
require("YourCode.jse");
Precompilation
ž  Nexe
—  Nexe is a command-line utility that compiles
your Node.js application into a single
executable file.
Build Tool
Make
ž  GNU Make is a tool which controls the
generation of executables and other
non-source files of a program from the
program's source files.
Grunt
ž  JavaScript Task Runner
—  minification
—  compilation
—  unit testing
—  …….
ž  Thousands of plugins
Questions?

More Related Content

What's hot

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.jsConFoo
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleTom Croucher
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
FwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsFwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsTimur Shemsedinov
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev ConfTom Croucher
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS ExpressDavid Boyer
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?Remy Sharp
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsMarcus Frödin
 

What's hot (20)

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
FwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsFwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.js
 
Beyond Phoenix
Beyond PhoenixBeyond Phoenix
Beyond Phoenix
 
Introduction to Flask Micro Framework
Introduction to Flask Micro FrameworkIntroduction to Flask Micro Framework
Introduction to Flask Micro Framework
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
Express js
Express jsExpress js
Express js
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
NodeJS
NodeJSNodeJS
NodeJS
 
NodeJS
NodeJSNodeJS
NodeJS
 
HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 

Similar to Node.js Agenda and Introduction

Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETGianluca Carucci
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsOhad Kravchick
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comVan-Duyet Le
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.jsChris Cowan
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationBen Hall
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 
Kraken Front-Trends
Kraken Front-TrendsKraken Front-Trends
Kraken Front-TrendsPayPal
 
Kraken
KrakenKraken
KrakenPayPal
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascriptEldar Djafarov
 

Similar to Node.js Agenda and Introduction (20)

NodeJS
NodeJSNodeJS
NodeJS
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
Introduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.comIntroduce about Nodejs - duyetdev.com
Introduce about Nodejs - duyetdev.com
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.js
 
Node js beginner
Node js beginnerNode js beginner
Node js beginner
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS Application
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Event driven programming -- Node.JS
Event driven programming -- Node.JSEvent driven programming -- Node.JS
Event driven programming -- Node.JS
 
Kraken Front-Trends
Kraken Front-TrendsKraken Front-Trends
Kraken Front-Trends
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
 
Kraken
KrakenKraken
Kraken
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Jaap : node, npm & grunt
Jaap : node, npm & gruntJaap : node, npm & grunt
Jaap : node, npm & grunt
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
 

More from Alex Su

One click deployment
One click deploymentOne click deployment
One click deploymentAlex Su
 
Scrum Introduction
Scrum IntroductionScrum Introduction
Scrum IntroductionAlex Su
 
Redis Introduction
Redis IntroductionRedis Introduction
Redis IntroductionAlex Su
 
Python decorators
Python decoratorsPython decorators
Python decoratorsAlex Su
 
Using puppet
Using puppetUsing puppet
Using puppetAlex Su
 
JMS Introduction
JMS IntroductionJMS Introduction
JMS IntroductionAlex Su
 
Spring Framework Introduction
Spring Framework IntroductionSpring Framework Introduction
Spring Framework IntroductionAlex Su
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionAlex Su
 
Cascading introduction
Cascading introductionCascading introduction
Cascading introductionAlex Su
 

More from Alex Su (9)

One click deployment
One click deploymentOne click deployment
One click deployment
 
Scrum Introduction
Scrum IntroductionScrum Introduction
Scrum Introduction
 
Redis Introduction
Redis IntroductionRedis Introduction
Redis Introduction
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Using puppet
Using puppetUsing puppet
Using puppet
 
JMS Introduction
JMS IntroductionJMS Introduction
JMS Introduction
 
Spring Framework Introduction
Spring Framework IntroductionSpring Framework Introduction
Spring Framework Introduction
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
 
Cascading introduction
Cascading introductionCascading introduction
Cascading introduction
 

Recently uploaded

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Recently uploaded (20)

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

Node.js Agenda and Introduction

  • 1.
  • 2. Agenda ž  Introduction ž  Package Manager ž  Web Framework ž  Testing ž  Callback Hell ž  Obfuscator ž  Build Tool
  • 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 )
  • 15. Hello World Create hello-world.js console.log(‘Hello World’); On the command line run node hello-world.js You should see Hello World
  • 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.
  • 19. NPM ž  Simple CLI tools ž  Register registry.npmjs.org ž  Web site npmjs.org ž  Included in node.js since 0.6 ž  Git friendly
  • 20. NPM Usage ž  npm search express ž  npm info express ž  npm install -g express ž  npm update ž  npm publish
  • 21. NPM Usage ž  npm install ./package.tgz ž  npm install sax --save ž  npm install node-tap --save-dev ž  npm install dtrace-provider --save-optional ž  npm install https://github.com/indexzero/forever/ tarball/v0.5.6
  • 22. Module Metas ž  package.json { "name": "my-website", "version": "0.0.1", "dependencies": { "express": "2.4.7", "jade": ">= 0.0.1", "oauth": ">= 0.9.5" } }
  • 24. Virtual Environment ž  nvm (starred 3884 on github) —  Simple bash script to manage multiple active node.js versions $ nvm install 0.10.29 $ nvm ls v0.10.29 current: v0.10.29 $ nvm use 0.10.29 Now using node v0.10.29 $ node --version v0.10.29
  • 25. Virtual Environment ž  nave (starred 645 on github) —  Virtual Environments for Node —  run on various node.js builds $ nave install latest $ nave ls src: 0.10.28 0.11.13 installed: 0.10.28 0.11.13 $ nave use 0.11.13 Already installed: 0.11.13 using 0.11.13 $ node --version v0.11.13
  • 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.
  • 28. Express ž  Generate an app $ npm install -g express-generator $ express --css stylus myapp create : myapp create : myapp/package.json create : myapp/app.js create : myapp/public create : myapp/public/javascripts create : myapp/public/images create : myapp/routes create : myapp/routes/index.js create : myapp/routes/users.js create : myapp/public/stylesheets create : myapp/public/stylesheets/style.styl create : myapp/views create : myapp/views/index.jade create : myapp/views/layout.jade create : myapp/views/error.jade create : myapp/bin create : myapp/bin/www install dependencies: $ cd myapp && npm install run the app: $ DEBUG=myapp ./bin/www
  • 29. Express Middleware ž  Middleware is any number of functions that are invoked by the Express.js routing layer before your final request handler is
  • 30. Express Middleware var app = express(); app.use(function(req, res, next) { console.log('%s %s', req.method, req.url); next(); }); app.get('/', function(req, res, next) { res.send('Hello World!'); }); app.get('/help', function(req, res, next) { res.send('Nope.. nothing to see here'); });
  • 31. Express Middleware ž  body-parser —  body —  co-body —  raw-body ž  compression ž  connect-timeout ž  cookie-parser ž  cookie-session ž  csurf ž  errorhandler ž  express-session ž  method-override ž  morgan ž  response-time ž  serve-favicon ž  serve-index ž  serve-static ž  vhost
  • 32. Express I18N app.js var i18n = require('i18n'); app.use(i18n.init); app.use(function (req, res, next) { res.locals.__ = function () { return function (text, render) { return i18n.__.apply(req, arguments); }; }; next(); }); en.js { "Home": "Home", "About Us": "About Us", "Program": "Program", "Venue": "Venue", "Sponsors": "Sponsors" } menu.hjs <li>{{#__}}Home{{/__}}</li> <li>{{#__}}About Us{{/__}}</li> <li>{{#__}}Program{{/__}}</li> <li>{{#__}}Venue{{/__}}</li> <li>{{#__}}Sponsors{{/__}}</li> menu.html <li>Home</li> <li>About Us</li> <li>Program</li> <li>Venue</li> <li>Sponsors</li>
  • 33. Express Authentication ž  Passport —  authentication middleware for Node.js. app.post('/login', passport.authenticate('local'), function(req, res) { res.redirect('/users/' + req.user.username); }); app.use(function(req, res, next) { if (!req.session.userid) { return res.redirect(url); } next(); });
  • 34. Template Engine ž  Jade ž  EJS ž  Hogan.js
  • 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>
  • 39. Redis Driver $ npm install redis hiredis var redis = require("redis"), client = redis.createClient(); // if you'd like to select database 3, instead of 0 (default), call // client.select(3, function() { /* ... */ }); client.on("error", function (err) { console.log("Error " + err); }); client.set("string key", "string val", redis.print); client.hset("hash key", "hashtest 1", "some value", redis.print); client.hset(["hash key", "hashtest 2", "some other value"], redis.print); client.hkeys("hash key", function (err, replies) { console.log(replies.length + " replies:"); replies.forEach(function (reply, i) { console.log(" " + i + ": " + reply); }); client.quit(); });
  • 40. Redis Sentinel Driver $ npm install redis hiredis redis-sentinel var sentinel = require('redis-sentinel'); var endpoints = [ {host: '127.0.0.1', port: 26379}, {host: '127.0.0.1', port: 26380} ]; var opts = {}; var masterName = 'mymaster'; var redisClient = sentinel.createClient(endpoints, masterName, opts);
  • 41. Mongo Driver $ npm install mongodb var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://192.168.68.234:27017/qcloud', function(err, db) { if(err) throw err; var collection = db.collection('device'); collection.find({'device_name':'alexnas'}).toArray(function(err, results) { console.dir(results); db.close(); }); });
  • 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.
  • 46. Mocha var assert = require("assert"); describe('Test', function() { var foo; beforeEach(function() { console.log('setup'); foo = 'bar'; }); afterEach(function() { console.log('teardown'); }); it('#test1', function() { console.log('run test1'); assert.equal(foo, 'bar'); }); });
  • 47. Nodeunit module.exports = { setUp: function (callback) { console.log('setup'); this.foo = 'bar'; callback(); }, tearDown: function (callback) { console.log('teardown'); callback(); }, test1: function (test) { console.log('run test1'); test.equals(this.foo, 'bar'); test.done(); } };
  • 49. Callback Hell doAsync1(function() { doAsync2(function() { doAsync3(function() { doAsync4(function() { }); }); }); });
  • 50. Callback Hell ž  An example from http://callbackhell.com/ fs.readdir(source, function(err, files) { if (err) { console.log('Error finding files: ' + err) } else { files.forEach(function(filename, fileIndex) { console.log(filename) gm(source + filename).size(function(err, values) { if (err) { console.log('Error identifying file size: ' + err) } else { console.log(filename + ' : ' + values) aspect = (values.width / values.height) widths.forEach( function(width, widthIndex) { height = Math.round(width / aspect) console.log('resizing ' + filename + 'to ' + height + 'x' + height) this.resize(width, height).write(destination + 'w' + width + '_' + filename, function(err) { if (err) console.log('Error writing file: ' + err) }) }.bind(this)) } }) }) } })
  • 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); });
  • 56. generator approach ž  Generators are lightweight co-routines for JavaScript. ž  Available in Node >=0.11.2 or above
  • 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); })()
  • 59. Obfuscator ž  YUI Compressor ž  Google Closure Compiler ž  minifyjs ž  uglify-js uglifyjs app.js -m -o app-min.js ž  node-obfuscator obfuscator --entry app.js app.js routes/index.js routes/user.js
  • 60. Obfuscator ž  Write your extension —  Implement encrypt/decrypt functions require.extensions[".jse"] = function (m) { m.exports = MyNativeExtension.decrypt(fs.readFileSync(m.filename)); }; require("YourCode.jse");
  • 61. Precompilation ž  Nexe —  Nexe is a command-line utility that compiles your Node.js application into a single executable file.
  • 63. Make ž  GNU Make is a tool which controls the generation of executables and other non-source files of a program from the program's source files.
  • 64. Grunt ž  JavaScript Task Runner —  minification —  compilation —  unit testing —  ……. ž  Thousands of plugins