You are on page 1of 91

e

Node.js Taiwan

Node.js

Little Book

Node.js 0.6.7
Node.js Taiwan
Node.js

ContPub Press

Node.js Taiwan

Node.js

Node.js Taiwan

2012 05 02

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . .

0.1

1 Node.js

2 JavaScript NodeJS

11

2.1

Event Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

11

2.2

Scope Closure . . . . . . . . . . . . . . . . . . . . . . . . . .

12

2.3

Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

13

2.4

CPSContinuation-Passing Style . . . . . . . . . . . . . . . .

16

2.5

Currying . . . . . . . . . . . . . . . . . . . . .

17

2.6

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

18

3 Node.js

25

3.1

Ubuntu Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . .

25

3.2

Other Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

26

3.3

Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

26

4 Node.js

29

4.1

node.js http . . . . . . . . . . . . . . . . . . . . . .

29

4.2

node.js http . . . . . . . . . . . . . . . . . . . . . . .

31

4.3

node.js . . . . . . . . . . . . . . . . . . . . . . . . . .

34

4.4

node.js http . . . . . . . . . . . . . . . . . . . . .

36

4.5

node.js http GET . . . . . . . . . . . . . . . . . . . .

38

4.6

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

40

5 NPM

41

5.1

NPM . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

41

5.2

NPM . . . . . . . . . . . . . . . . . . . . . . .

45

5.3

. . . . . . . . . . . . . . . . . . . . . . . .

48

5.4

package.json . . . . . . . . . . . . . . . . . . . . . . . . . .

49

6 Express

51

6.1

Express . . . . . . . . . . . . . . . . . . . . . . . . . . . .

51

6.2

Express . . . . . . . . . . . . . . . . . . . . . . . . . .

52

6.3

Express . . . . . . . . . . . . . . . . . . . . . . . . . .

52

6.4

Express middleware . . . . . . . . . . . . . . . . . . . . . . . . .

55

6.5

Express . . . . . . . . . . . . . . . . . . . . . . . . . .

56

6.6

Express GET . . . . . . . . . . . . . . . . . . . . . . .

57

6.7

Express POST . . . . . . . . . . . . . . . . . . . . . .

60

6.8

Express AJAX . . . . . . . . . . . . . . . . . . . . . .

63

6.9

. . . . . . . . . . . . . . . . . . . . . . . . . . .

67

7 CoeeScript

69

8 Hubot Plurk Adapter

71

ii

8.1

. . . . . . . . . . . . . . . . . . . . . . . . . . .

71

8.2

Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . .

71

8.3

Robot API . . . . . . . . . . . . . . . . . . . . . . . . .

72

8.4

. . . . . . . . . . . . . . . . . . . . . . . . . . .

78

9 Node.js
9.1

log.io . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

10
10.1 Express . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11

79
79
81
81
83

11.1 Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . .

83

11.2 Node.js . . . . . . . . . . . . . . . . . . . . . . . . .

84

11.3 Node.js . . . . . . . . . . . . . . . . . . . . . . . . .

84

11.4 Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . .

84

iii

iv

Node.js GitHub
ContPubContinuous Publishing
PDFEPUBMOBI HTML

GitHub
http://book.nodejs.tw/
ContPub

http://contpub.org/read/nodejs-wiki-book
Node.js

Node.js CC -

Node.js Wiki Book book is licensed under the Attribution-NonCommercial 3.0


Unported license. You should not have paid for this book.

Node.js

http://creativecommons.org/licenses/by-nc/3.0/legalcode

Node.js Taiwan
Caesar Chi (clonn)
Fillano Feng ( llano)
Kyle Lin (lyhcode)
Node.js Taiwan

http://book.nodejs.tw/
PDF 7
http://contpub.org/download/nodejs-wiki-book.pdf
EPUB iPadiPhone
http://contpub.org/download/nodejs-wiki-book.epub
MOBI Kindle
http://contpub.org/download/nodejs-wiki-book.mobi

http://github.com/nodejs-tw/nodejs-wiki-book

Node.js

0.1
Node.js
Node.js Taiwan
1.
2. E-Mail
Node.js Taiwan
3.
4. E-Mail

5. Node.js Taiwan

0.1.

Node.js

Node.js JavaScript 0.4.x v0.6.0

nodeJS
nodeJS.tw javascript

CoeeScript

Node.js

Node.js

Node.js (Web Application Framework)

Ryan Dahl NodeJS Joyent ()


NodeJS Apache
(buer)
V8 JavaScript Engine
JavaScript

JavaScript JavaScript
()
(API) JavaScript JavaScript
CommonJS (standard library) JavaScript
Ruby Python Java NodeJS
JavaScript CommonJS CommonJS API
CommonJS (compliant) JavaScript

Node.js
JavaScript CommonJS NodeJS
JavaScript XMLHttpRequest

XMLHttpRequest Telnet /
FTP / NTP SMTP
Sockets TCP ( UDP)
PHP Java Python Perl Ruby
Sockets API JavaScript
Sockets CommonJS
CommonJS NodeJS
Sockets API
JavaScript Lambda (anonymous
function)
var proc1 = function(op, x) { return op(x);
}
var op1 = function(x) { return x+1; } var op2 = function(x) { return x*x;
}
proc1(op1, 3); // result is 4 proc1(op2, 5); // result is 25
JavaScript Closure
NodeJS CommonJS Callback
JavaScript NodeJS (Module)

10 NodeJS
NodeJS V8 Javascript
V8 Javascript

Javascript

(connection) (thread)
(block)
8

1. Node.js

Node.js
NodeJS (connection)
epoll, kqueue, /dev/poll, select
heap (Sleep)
callback CPU
Javascript request callback
Block
Callback NodeJS Comet(long pulling) Request
Server NodeJS
NodeJS (Node package
management) NodeJS
npm
node.js v0.6.8 API http://
nodejs.org <http://nodejs.org> linux, windows
http:// nodejs.tw <http:// node.js.tw>
node.js

Node.js

10

1. Node.js

JavaScript NodeJS

JavaScript
NodeJS
Event LoopScope Callback
cpscurrying ow control

2.1 Event Loop


Javascript
jQuery John Resig timer
How JavaScript Timers Work
Javascript global scope
John Resig timer
queue queue
event loop
John Resig Nicholas C. Zakas Professional Javascript
for Web Developer 2nd edition http://yuiblog.com/assets/pdf/
zakas-projs-2ed-ch18.pdf598
Javascript
11

Node.js
event loop
I/O render, re ow

lock dead lock

instance NodeJS
event loop

process.nextTick

event loop
alert() Javascript timer

delay alert

2.2 Scope Closure


JavaScript Scope
Lexical Scope

scope
local scope
Closure
function outter(arg1) {
//arg1 free_variable1 inner
var free_variable1 = 3;
return function inner(arg2) {

12

2. JavaScript NodeJS

Node.js

var local_variable1 =2;//arg2 local_variable1 inner


return arg1 + arg2 + free_variable + local_variable1;
};
}

var a = outter(1);// a outter inner var b =


a(4);// inner outter
outter arg1 free variable1
console.log(b);// 10
Javascript scope global eval
closure

Closure

Javascript Engine
Closure

2.3 Callback
Callback JavaScript
JavaScript functional language Javascript
(higher order function
rst class function
)
Javascript
callback
Javascript NodeJS
EventEmitter NodeJS

mixin.on(,callback
2.3. Callback

13

Node.js
) .addListener(,callback )
.emit(, ...)
callback Observer Pattern DOM
addEventListener NodeJS
callback
callback

var p client = new Db(integration tests 20, new Server(127.0.0.1, 27017,


{}), {pk:CustomPKFactory}); p client.open(function(err, p client) {
p client.dropDatabase(function(err, done) {
p client.createCollection(test custom key, function(err, collection) {
collection.insert({a:1}, function(err, docs) {

collection. nd({ id:new ObjectID(aaaaaaaaaaaa)}, function(err, cursor) {


cursor.toArray(function(err, items) {
test.assertEquals(1, items.length); p client.close();
});
});
});
});
});
});
mongodb
callback
callback

callback event handler


14

2. JavaScript NodeJS

Node.js
handler
var http = require(http); var tools = {
cookieParser: function(request, response) { if(request.headers[Cookie])
{ //do parsing } }
}; var server = http.createServer(function(request, response) {
this.emit(init, request, response); //...
}); server.on(init, tools.cookieParser); server.listen(8080, 127.0.0.1);
tools module tools.js
module.exports = { cookieParser:

function(request,

response)

if(request.headers[Cookie]) { //do parsing } }


};

var http = require(http);


var server = http.createServer(function(request, response) { this.emit(init, request, response); //...
});

server.on(init,

require(./ tools).cookieParser);

server.listen(8080,

127.0.0.1);
cookieParser nodeunit

var testCase = require(nodeunit).testCase; module.exports = testCase({


setUp: function(cb) { this.request = { headers:

{ Cookie:

name1:val1; name2:val2 } }; this.response = {}; this.result


= {name1:val1,name2:val2};
cb();
}, tearDown: function(cb) {
cb();
2.3. Callback

15

Node.js
}, normal case: function(test) {
test.expect(1);

var

obj

tools).cookieParser(this.request,

require(./
this.response);

test.deepEqual(obj, this.result); test.done();


}
});

2.4 CPSContinuation-Passing Style


cps callback callback
callback
continuation-passing style cps
callback cps callback callback

<html>

<body>

<div

id=panel

style=visibility:hidden></ div>

</ body> </ html> <script> var request = new XMLHttpRequest(); request.open(GET, test749.txt? timestamp=+new Date().getTime(), true); request.addEventListener(readystatechange, function(next){
return function() { if(this.readyState===4&&this.status===200) {
next(this.responseText);//<== cps callback
} };
}(function(str){//<== cps callback
document.getElementById(panel).innerHTML=str;

docu-

ment.getElementById(panel).style.visibility = visible;
}), false); request.send(); </script>
2-6

16

2. JavaScript NodeJS

Node.js

2.5 Currying
cps cps callback
onreadystatechange
/
Closure next

scope
<script> var accu=0,count=10; for(var i=0; i<count; i++) {
setTimeout(
function(){ count; accu+=i; if(count<=0)
console.log(accu)
}
, 50)
} </script>
100 45 setTimeout i 10
Closure i
<script> var accu=0,count=10; for(var i=0; i<count; i++) {
setTimeout(
function(i) { return function(){ count;
accu+=i; if(count<=0)
console.log(accu)
};
}(i)
, 50)

2.5. Currying

17

Node.js
} // </script>

function add(m, n) { return m+n;


} var a = add(20, 10); console.log(a);
add

function add(m) {
return function(n) { return m+n;
};
} var wait another arg = add(20);// var a = function(arr) {
var ret=0; for(var i=0;i<arr.length;i++) ret+=arr[i]; return ret;
}([1,2,3,4]);// var b = wait another arg(a);//
console.log(b);

...Currying

...

2.6
sync async callback async callback

http://howtonode.org/control- ow
http://howtonode.org/control- ow-part-ii
18

2. JavaScript NodeJS

Node.js

http://howtonode.org/control- ow-part-iii
http://blog.mixu.net/2011/02/02/essential-node-js-patterns-and-snippets
NodeJS/Javascript mixu
pattern

mixu
var wait = function(callbacks, done) { console.log(wait start); var counter = callbacks.length; var results = []; var next = function(result) {//
results.push(result); if(counter == 0) {
done(results);// callback
} }; for(var i = 0; i < callbacks.length; i++) {//
callbacks[i](next); } console.log(wait end);
}
wait( [ function(next){ setTimeout(function(){ console.log(done a); var result =
500; next(result) }, 500); }, function(next){ setTimeout(function(){ console.log(done b); var result = 1000; next(result) },1000); }, function(next){
setTimeout(function(){ console.log(done c); var result = 1500; next(1500) },
1500); } ], function(results){ var ret = 0, i=0; for(; i<results.length; i++) { ret
+= results[i]; } console.log(done all. result: +ret); }
);
wait start wait end done a done b done c done all. result: 3000
wait

done()

Tim Caswell

2.6.

19

Node.js
NodeJS
fs readFile Currying
var fs = require(fs); var readFile = function(path) {
return function(callback, errback) {
fs.readFile(path, function(err, data) {
if(err) { errback();
} else { callback(data);
}
});
};
}
Tim Caswell Do.parallel wait

callback
cps
<script> function Wait(fns, done) {
var count = 0; var results = []; this.getCallback = function(index) {
count++; return (function(waitback) {
return function() { var

i=0,args=[];

for(;i<arguments.length;i++) {
args.push(arguments[i]);
} args.push(waitback); fns[index].apply(this,
args);
};
})(function(result) { results.push(result); if(count == 0) {

20

2. JavaScript NodeJS

Node.js

done(results);
}
});
}
} var a = new Wait(
[ function(waitback){ console.log(done a); var result = 500; waitback(result) }, function(waitback){ console.log(done b); var result =
1000; waitback(result) }, function(waitback){ console.log(done c); var
result = 1500; waitback(result) } ], function(results){ var ret = 0, i=0;
for(; i<results.length; i++) { ret += results[i]; } console.log(done all.
result: +ret); }
); var callbacks = [a.getCallback(0),a.getCallback(1),a.getCallback(0),a.getCallback(2)];
// callbacks setTimeout(callbacks[0],
500); setTimeout(callbacks[1], 1000); setTimeout(callbacks[2], 1500); setTimeout(callbacks[3], 2000); // callbacks done()
</script>

done a done b done a done c done all. result: 3500


Tim Caswell stephttps://
github.com/creationix/step
Promise.js
library XD
Promise http://blogs.msdn.com/b/rbuckton/archive/
2011/08/15/promise-js-2-0-promise-framework-for-javascript.aspx
Library
compile Bruno
Jouhier streamline.jshttps://github.com/Sage/streamlinejs

2.6.

21

Node.js

callback
serial.js
module.exports = function(funs) { var c = 0; if(!isArrayOfFunctions(funs)) {
throw(Argument type was not matched. Should be array of functions.);
} return function() {
var

args

Array.prototype.slice.call(arguments,

0);

if(!

(c>=funs.length)) {
c++; return funs[c-1].apply(this, args);
}
};
}
function isArrayOfFunctions(f ) { if(typeof f !== object) return false; if(!f.length)
return false; if(!f.concat) return false; if(!f.splice) return false; var i = 0; for(;
i<f.length; i++) {
if(typeof f[i] !== function) return false;
} return true;
}
testSerial.js fs path
callback
serial nested callbacks
var serial = require(./serial), fs = require(fs), path = ./dclient.js, cb = serial([ function(err, data) {
if(!err) {
if(data.isFile) { fs.readFile(path, cb);
22

2. JavaScript NodeJS

Node.js
}
} else { console.log(err);
}
}, function(err, data) {
if(!err) { console.log([ attened

by

searial:]);

con-

sole.log(data.toString(utf8));
} else { console.log(err);
}
}
]); fs.stat(path, cb);
fs.stat(path, function(err, data) { // callback if(!err) {
if(data.isFile) {
fs.readFile(path, function(err, data) { // callback if(!
err) {
console.log([nested

callbacks:]);

con-

sole.log(data.toString(utf8));
} else { console.log(err);
}
});
} else { console.log(err);
}
}
});
callback serial
cb callback cb

2.6.

23

Node.js
callback function serial

./dclient.js dnode testSerial.js

var dnode = require(dnode);


dnode.connect(8000, localhost, function(remote) {
remote.restart(function(str) { console.log(str); process.exit();
});
});

[ attened by searial:] var dnode = require(dnode);


dnode.connect(8000, localhost, function(remote) {
remote.restart(function(str) { console.log(str); process.exit();
});
});
[nested callbacks:] var dnode = require(dnode);
dnode.connect(8000, localhost, function(remote) {
remote.restart(function(str) { console.log(str); process.exit();
});
});
serial.js
callback

https://github.com/caolan/async

24

2. JavaScript NodeJS

Node.js

OS NodeJS NodeJS 0.4.8


Linux
NodeJS package
NodeJS

3.1 Ubuntu Linux


nvm
git clone git://github.com/creationix/nvm.git ~/.nvm
echo . ~/.nvm/nvm.sh >> ~/.bashrc
nvm install v0.6.14
nvm alias default v0.6.14

http:// dreamerslab.com/ blog/ tw/ how-to-setup-a-node-jsdevelopment-environment-on-ubuntu-11-04/


APT PPA

sudo apt-get install python-software-properties


sudo add-apt-repository ppa:chris-lea/node.js-devel

25

Node.js

sudo apt-get update


sudo apt-get install nodejs

3.2 Other Linux


Linux NodeJS

curl (wget)
git
g++ GNU C++
make GNU
sudo
git clone https://github.com/joyent/node.git
cd node
git checkout v0.6.7
./configure
make
sudo make install

nodeJS
node --version

3.3 Windows
nodeJS v0.6.0 windows native
node.exe linux
node

26

3. Node.js

Node.js
node.js <http://nodejs.org/#download>
windows native node.exe command line
command line node node.js

3.3. Windows

27

Node.js

28

3. Node.js

Node.js

nodeJS
javascript (function) (object)
nodeJS
nodeJS

4.1 node.js http


node.js <http://nodejs.org> HTTP
node.js
Hello world
Hello world node.js
node basic http hello world.js
var server,
ip

= 127.0.0.1,

port = 1337,
http = require(http);
server = http.createServer(function (req, res) {

29

Node.js

res.writeHead(200, {Content-Type: text/plain});


res.end(Hello World\n);
});
server.listen(port, ip);
console.log(Server running at http:// + ip + : + port);

ip: ip 127.0.0.1
port: http port 80
port 1337
node.js
require http http
Http createServer
http http server
(call back function) http (request,
response) Header

res.writeHead(200, {Content-Type: text/plain});


res.end(Hello World\n);

Http port, ip Http


listen Http
http.listen(port, ip);

console
javascript console node.js

(debug) console
console.log(Server running at http:// + ip + : + port);

30

4. Node.js

Node.js

4.2 node.js http


http
(rout) http
(request)
ip
hello world
server = http.createServer(function (req, res) {
console.log(req.url);
res.writeHead(200, {Content-Type: text/plain});
res.end(hello world\n);
});

node.js

http://127.0.0.1:1337/test
/test /favicon.ico/test
http

4.2. node.js http

31

Node.js
node.js

node.js

var server,
ip

= 127.0.0.1,

port = 1337,
http = require(http),
url = require(url),
path;
server = http.createServer(function (req, res) {
path = url.parse(req.url);
res.writeHead(200, {Content-Type: text/plain});
switch (path.pathname) {
case /index:
res.end(I am index.\n);
break;
case /test:
res.end(this is test page.\n);
break;
default:
res.end(default page.\n);
break;
}
});
server.listen(port, ip);
console.log(Server running at http:// + ip + : + port);

url path url


url

GET
http://127.0.0.1:1337/test?send=1
32

4. Node.js

Node.js
**req.url** /test?send=1 url

url.parse
path

path.pathname

/index index /test


test default

4.2. node.js http

33

Node.js

4.3 node.js
rount

html, css, javascript


File system <http://nodejs.org/docs/latest/api/
fs.html>

html
<!DOCTYPE html>
<html xmlns=http://www.w3.org/1999/xhtml xml:lang=zh-CN lang=zh-CN>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-7 />
<title>node.js index html file</title>
</head>
<body>

34

4. Node.js

Node.js

<h1>node.js index html file</h1>


</body>
</html>

node.js
var fs = require(fs),
filename = static/index.html,
encode = utf8;
fs.readFile(filename, encode, function(err, file) {
console.log(file);
});

** le system ** fs
readFile ( le path) , (encoding)
(callback) html

utf8 node.js byte raw


byte raw

error
error true error
false content content

4.3. node.js

35

Node.js

4.4 node.js http


http
html html

<!DOCTYPE html>
<html xmlns=http://www.w3.org/1999/xhtml xml:lang=zh-CN lang=zh-CN>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-7 />
<title>node.js index html file</title>
</head>
<body>
<h1>node.js index html file</h1>
</body>
</html>
<!DOCTYPE html>
<html xmlns=http://www.w3.org/1999/xhtml xml:lang=zh-CN lang=zh-CN>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-7 />
<title>node.js test html file</title>
</head>
<body>
<h1>node.js test html file</h1>
</body>
</html>
<!DOCTYPE html>
<html xmlns=http://www.w3.org/1999/xhtml xml:lang=zh-CN lang=zh-CN>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-7 />
<title>node.js static html file</title>
</head>
<body>
<h1>node.js static html file</h1>
</body>
</html>

36

4. Node.js

Node.js
http
var server,
ip

= 127.0.0.1,

port = 1337,
http = require(http),
url = require(url);
server = http.createServer(function (req, res) {
var path = url.parse(req.url);
});
server.listen(port, ip);
console.log(Server running at http:// + ip + : + port);

le system readFile
createServer
fs.readFile(filePath, encode, function(err, file) {
});

readFile
html Content-type
text/html html
fs.readFile(filePath, encode, function(err, file) {
res.writeHead(200, {Content-Type: text/html});
res.write(file);
res.end();
});

static

html

404 http header


http html

4.4. node.js http

37

Node.js

var server,
ip

= 127.0.0.1,

port = 1337,
http = require(http),
fs = require(fs),
folderPath = static,
url = require(url),
path,
filePath,
encode = utf8;
server = http.createServer(function (req, res) {
path = url.parse(req.url);
filePath = folderPath + path.pathname;
fs.readFile(filePath, encode, function(err, file) {
if (err) {
res.writeHead(404, {Content-Type: text/plain});
res.end();
return;
}
res.writeHead(200, {Content-Type: text/application});
res.write(file);
res.end();
});
});
server.listen(port, ip);
console.log(Server running at http:// + ip + : + port);

4.5 node.js http GET


http GET
http
GET
http GET URL
38

4. Node.js

Node.js

http://127.0.0.1/test?send=1&test=2

GET send 1
http GET (request)

query string
**javascript **
qs = require(querystring);

url URL
query
send=1&test=2
query string parse javascript
GET
path = url.parse(req.url);
parameter = qs.parse(path.query);

node.js http GET


var server,
ip

= 127.0.0.1,

port = 1337,
http = require(http),
qs = require(querystring),
url = require(url);
server = http.createServer(function (req, res) {
var path = url.parse(req.url),
parameter = qs.parse(path.query);
console.dir(parameter);
res.writeHead(200, {Content-Type: text/plain});
res.write(Browser test GET parameter\n);
res.end();
});

4.5. node.js http GET

39

Node.js

server.listen(port, ip);
console.log(Server running at http:// + ip + : + port);

node.js

Server running at http://127.0.0.1:1337


{ send: 1, test: 1 }

4.6
http
http
node.js
javascript node.js

node.js

40

4. Node.js

NPM

npm Node Package Manager Node.js package


Perl ppm PHP PEAR npm npm install
module name
npm Node.js packages
registrynpm
npm

npm

5.1 NPM
Node.js 0.6.3 npm

npm
npm -v

41

Node.js

npm npm -v 1.1.0-2


Node.js npm

Windows
Node.js for Windows 0.6.2 npm nodejs.org
npm
Windows
Node.js npm npm

http://npmjs.org/dist/
npm Fancy Windows Install
npm-1.1.0-3.zip Node.js
C:\Program Files\nodejs
Node.js
npm.cmd
node modules

Linux
Ubuntu Linux NPM Unocial PPA repository
apt-get npm

42

5. NPM

Node.js

Ubuntu Linux apt-get npm


sudo apt-get install python-software-properties
sudo add-apt-repository ppa:gias-kay-lee/npm
sudo apt-get update
sudo apt-get install npm

npm install.sh Linux

1. curl curl --version


2. Node.js PATH
3. Node.js 0.4.x
npm
curl http://npmjs.org/install.sh | sh

install.sh
npm@1.0.105 /home/USERNAME/local/node/lib/node_modules/npm
It worked

Mac OS X
Node.js npm MacPorts
Node.js MacPorts npm

MacPorts npm npm

5.1. NPM

43

Node.js

MacPorts
MacPorts OS X 10.6
10.7
http://www.macports.org/

MacPorts port -v MacPorts

npm MacPorts npm

sudo port -d selfupdate

npm
sudo port install npm

Node.js MacPorts MacPorts


npm MacPorts npm nodejs
MacPorts nodejs
nodejs
MacPorts curlsudo port install curl
Linux install.sh npm

NPM
npm command-line tool

npm
npm -v

npm --version

npm

44

5. NPM

Node.js

1.1.0-2

5.2 NPM
npm 6000 packages npm registry

http://search.npmjs.org/
coee-script
coee-script

npm

coee-script
npm search coffee-script

5.2. NPM

45

Node.js

express
npm install coffee-script

npm install
Working Directory node modules
Windows npm install
C:\project1
npm node modules
C:\project1\node modules

C:\project1\node modules\coffee-script

node modules

npm install local()

global
npm node modules
C:\Program Files\nodejs\node modules

46

5. NPM

Node.js

express express coee-script coffee

local
node modules .bin .bin PATH

npm install -g -global global


npm install -g coffee-script
npm install -g express

global

npm ERR! Error: EACCES, permission denied ...


npm ERR!
npm ERR! Please try running this command again as root/Administrator.

Windows 7 2008
npm Administrator

Mac OS X Linux sudo


sudo npm install -g express
Linux root sudo su - root
root

-g npm install -g coffee-script


coffee
coffee -v

5.2. NPM

47

Node.js

CoffeeScript version 1.2.0

5.3
search install npm
commands
npm help
npm help

where <command> is one of:


adduser, apihelp, author, bin, bugs, c, cache, completion,
config, deprecate, docs, edit, explore, faq, find, get,
help, help-search, home, i, info, init, install, la, link,
list, ll, ln, login, ls, outdated, owner, pack, prefix,
prune, publish, r, rb, rebuild, remove, restart, rm, root,
run-script, s, se, search, set, show, star, start, stop,
submodule, tag, test, un, uninstall, unlink, unpublish,
unstar, up, update, version, view, whoami

npm help command


npm help list

npm
list
npm list

48

5. NPM

Node.js

-- coffee-script@1.2.0
- express@2.5.6
- connect@1.8.5
| -- formidable@1.0.8
-- mime@1.2.4
-- mkdirp@0.0.7
-- qs@0.4.1

npm show express

npm update

npm update express

npm uninstall express

5.4 package.json
Node.js package.json

5.4. package.json

49

Node.js

package.json
{
name: application-name
, version: 0.0.1
, private: true
, dependencies: {
express: 2.5.5
, coffee-script: latest
, mongoose: >= 2.5.3
}
}

name version
dependencies

express: 2.5.5
// 2.5.5 express
coffee-script: latest
// coee-script
mongoose: >= 2.5.3
// 2.5.3 mongoose

>=latest

50

5. NPM

Express

node.js http
node.js
express [Express](http://expressjs.com/)
node.js http server http
service module

TJ Holowaychuk
(route)http GET/POST/PUTjs
html template engine

6.1 Express
NPM

51

Node.js

6.2 Express
express hello world
var app = require(express).createServer(),
port = 1337;
app.listen(port);
app.get(/, function(req, res){
res.send(hello world);
});
console.log(start express server\n);

node.js http
app.get

6.3 Express
Express http
app.get
// ... Create http server
app.get(/, function(req, res){
res.send(hello world);
});
app.get(/test, function(req, res){
res.send(test render);
});
app.get(/user/, function(req, res){
res.send(user page);
});

52

6. Express

Node.js
app.get
(call back function)
createServer requestresponse
url

// ... Create http server


app.get(/user/:id, function(req, res){
res.send(user: + req.params.id);
});
app.get(/:number, function(req, res){
res.send(number: + req.params.number);
});

:number
req.params.number url
/user/:id/user/xxx
req.params.id xxx
express

var app = require(express).createServer(),


port = 1337;
app.listen(port);

app.get(/^\/ip?(?:\/(\d{2,3})(?:\.(\d{2,3}))(?:\.(\d{2,3}))(?:\.(\d{2,3})))?
res.send(req.params);
});

/ip ip ip
ip
localhost:3000/ip/
255.255.100.10
6.3. Express

53

Node.js

/**
* @overview
*
* @author Caesar Chi
* @blog clonn.blogspot.com
* @version 2012/02/26
*/
// create server.
var app = require(express).createServer(),
port = 1337;
app.listen(port);
// normal style
app.get(/, function(req, res){
res.send(hello world);
});
app.get(/test, function(req, res){
res.send(test render);
});
// parameter style
app.get(/user/:id, function(req, res){
res.send(user: + req.params.id);
});
app.get(/:number, function(req, res){
res.send(number: + req.params.number);
});
// REGX style

app.get(/^\/ip?(?:\/(\d{2,3})(?:\.(\d{2,3}))(?:\.(\d{2,3})))?/, function(req
res.send(req.params);
});
app.get(*, function(req, res){
res.send(Page not found!, 404);

54

6. Express

Node.js

});
console.log(start express server\n);

6.4 Express middleware


Express middleware
middleware next
middleware
// .. create http server
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session());

middleware app.use
responserequestnext
next middleware

localhost:1337/

first middle ware


second middle ware
execute middle ware
end middleware function

middleware app.use
middleware url
app.get middleware app.get
request, response, next
next

6.4. Express middleware

55

Node.js

6.5 Express

express app.all

/**
* @overview
*
* @author
* @version 2012/02/26
*/
// create server.
var app = require(express).createServer(),
port = 1337,
users = [
{name: Clonn},
{name: Chi}
];
app.listen(port);
app.all(/user/:id/:op?, function(req, res, next){
req.user = users[req.params.id];
if (req.user) {
next();
} else {
next(new Error(cannot find user + req.params.id));
}
});
app.get(/user/:id, function(req, res){
res.send(viewing + req.user.name);
});
app.get(/user/:id/edit, function(req, res){
res.send(editing + req.user.name);
});

56

6. Express

Node.js

app.get(/user/:id/delete, function(req, res){


res.send(deleting + req.user.name);
});
app.get(*, function(req, res){
res.send(Page not found!, 404);
});
console.log(start express server\n);

app.all
app.get
/
user/0 app.all next /
user/:id /user/0/edit /
user/:id/edit

6.6 Express GET


GET
<!DOCTYPE html>
<html>
<head>

<meta http-equiv=Content-Type content=text/html; charset=utf8


<title>Node.js (1)</title>

<link rel=stylesheet href=css/style.css type=text/css medi


</head>
<body>
<h1>Node.js -</h1>

<form id=signup method=GET action=http://localhost:3000/Sig

<label> </label><input type=text id=usern


<label> </label><input type=text id=email
<input type=submit value= /><br>
</form>
</body>
</html>

6.6. Express GET

57

Node.js
9 form
method GET action http://localhost:3000/Signup
/Signup URL Path
Signup
GET URL
URL
http://localhost:3000/Signup?username=xxx&email=xxx

:
URL
Signup
username email
username email
Signup
// load module
var url

= require(url);

urlData = url.parse(req.url,true);
action = urlData.pathname;
res.writeHead(200, {Content-Type:text/html; charset=utf-8});
if (action === /Signup) {
user = urlData.query;
res.end(<h1> + user.username + </h1><p>
}

url module URL


url.parse url req.url
ture querystring false
urlData.query true
url.parse urlData
action pathname
html (Header)
58

6. Express

Node.js
/Signup urlData.query user
user.username user.email
node.js

node.js
var http = require(http),
url

= require(url),

fs

= require(fs),

server;
server = http.createServer(function (req,res) {
var urlData,
encode

= utf8,

filePath = view/express_get_example_form.html,
action;
urlData = url.parse(req.url,true);
action = urlData.pathname;
res.writeHead(200, {Content-Type:text/html; charset=utf-8});
if (action === /Signup) {
user = urlData.query;

res.end(<h1> + user.username + </h1><p>


}
else {
fs.readFile(filePath, encode, function(err, file) {
res.write(file);
res.end();
});
}
});
server.listen(3000);
console.log(Server : + new Date());

6.6. Express GET

59

Node.js

6.7 Express POST


html POST form action
POST html
<!DOCTYPE html>
<html>
<head>

<meta http-equiv=Content-Type content=text/html; charset=utf8


<title>Node.js (1)</title>

<link rel=stylesheet href=css/style.css type=text/css medi


</head>
<body>
<h1>Node.js -</h1>

<form id=signup method=POST action=http://localhost:3000/Si

<label> </label><input type=text id=usern


<label> </label><input type=text id=email
<input type=submit value= /><br>
</form>
</body>
</html>

node.js GET
qs

= require(querystring),

if (action === /Signup) {


formData = ;
req.on(data, function (data) {
formData += data;
});
req.on(end, function () {
user = qs.parse(formData);

res.end(<h1> + user.username + </h1><p>


});
}

60

6. Express

Node.js
querystring moduel POST
formData
GET req url
req
JavaScript addEventListener node.js
on data Web Server

end
POST
data formData <

end qs.parse formData


formData
username=wordsmith&email=wordsmith%40some.where

qs.parse querystring
{username=wordsmith&email=wordsmith%40some.where}

user GET
response user.username user.email

node.js web server


POST

var http = require(http),


url

= require(url),

fs

= require(fs),

qs

= require(querystring),

server;
server = http.createServer(function (req,res) {
var urlData,

6.7. Express POST

61

Node.js

encode

= utf8,

filePath = view/express_post_example_form.html,
formData,
action;
urlData = url.parse(req.url,true);
action = urlData.pathname;
res.writeHead(200, {Content-Type:text/html; charset=utf-8});
if (action === /Signup) {
formData = ;
req.on(data, function (data) {
formData += data;
});
req.on(end, function () {
user = qs.parse(formData);

res.end(<h1> + user.username + </h1><p>


});
}
else {
fs.readFile(filePath, encode, function(err, file) {
res.write(file);
res.end();
});
}
});
server.listen(3000);
console.log(Server : + new Date());

62

6. Express

Node.js

6.8 Express AJAX


Node.js Ajax
client GET POST
JSON Ajax JSON
HTML
JSON
Ajax

HTML
HTML
<!DOCTYPE html>
<html>
<head>
<title>Node.js (3)</title>

<link rel=stylesheet href=/css/style.css type=text/css media=

<script src=https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jque
</head>
<body>
<h1>Node.js - ( Ajax)</h1>
<form id=signup action=/Signup method=POST>

<label> </label><input type=text id=username

<label> </label><input type=text id=email name


<input type=submit value= /><br>
</form>
<div id=result>
</div>
<script type=text/javascript>
$(function(){
$(#signup input[type=submit]).click(function(e){
var user = {};
user.username = $(#username).val();
user.email = $(#email).val();
$.post(/Signup,user,function(data){
greet(data)
});

6.8. Express AJAX

63

Node.js

e.preventDefault();
});
var greet = function(msg){
var resultNode = $(#result),

greeting = $(<h2>Hi,+msg.username+, id
$(#signup).hide();
resultNode.html();
resultNode.append(greeting);
};
});
</script>
</body>
</html>

HTML
Google CDN jQuery Ajax
HTML JavaScript
( jQuery )
jQUery submit click
username email user
jQuery $.post user Server
greet function
user

Server usernameemail id 3


Ajax
node.js
var fs

64

= require(fs),

6. Express

Node.js

qs

= require(querystring);

if (action === /Signup) {


formData = ;
req.on(data, function (data) {
formData += data;
});
req.on(end, function () {
var msg;
user = qs.parse(formData);
user.id = 123456;
msg = JSON.stringify(user);

res.writeHead(200, {Content-Type:application/json; charset=utf-8,Co


res.end(msg);
});
}

POST
user id Server
Client Server
msg user JSON
JSON.stringify V8
Client JSON
Content-type Content-Length Client
Server node.js

node.js
var http = require(http),
url

= require(url),

fs

= require(fs),

qs

= require(querystring),

server;

6.8. Express AJAX

65

Node.js

server = http.createServer(function (req,res) {


var urlData,
encode

= utf8,

filePath = view/express_ajax_example_form.html,
formData,
action;
urlData = url.parse(req.url,true);
action = urlData.pathname;
if (action === /Signup) {
formData = ;
req.on(data, function (data) {
formData += data;
});
req.on(end, function () {
var msg;
user = qs.parse(formData);
user.id = 123456;
msg = JSON.stringify(user);

res.writeHead(200, {Content-Type:application/json;,Content-Leng
res.end(msg);
});
}
else {
fs.readFile(filePath, encode, function(err, file) {
res.writeHead(200, {Content-Type:text/html; charset=utf-8});
res.write(file);
res.end();
});
}
});
server.listen(3000);

66

6. Express

Node.js

console.log(Server : + new Date());

6.9
[Node.JS (1)- GET ] (http://ithelp.ithome.com.tw/
question/10087402)
[Node.JS (2)- POST ] (http://ithelp.ithome.com.tw/
question/10087489)
[Node.JS (3)- Ajax ] (http://ithelp.ithome.com.tw/
question/10087627)

6.9.

67

Node.js

68

6. Express

CoeeScript

Spine
Hem
Spine.app
Lets Have a Cup of CoeeScript
es5-shim ECMAScript 5 compatibility shims for legacy JavaScript engines
ES.next
node-iform - A middleware for node-validator https://github.com/guileen/nodeiform

69

Node.js

70

7. CoeeScript

Hubot Plurk Adapter

8.1
CoeeScript Github Hubot

Hubot Adapter
Node.js Module
Hubot bin/hubot npm install

Node.JS
npm

8.2 Adapter

package.json
plurk.coee

71

Node.js
Node.JS Coding
package.json
{
name: hubot-plurk,
version: 0.1.1,
main: ./plurk,
dependencies:
{
hubot: >=2.0.5,
oauth: ,
cron:
}
}

Node.JS cron Module Plurk OAuth


OAuth
*Hubot hubot-
*

8.3 Robot API


Hubot - Twitter Adapter
OAuth Twitter Streaming Plurk
Comet
plurk.coee
Robot = require(hubot).robot()
Adapter = require(hubto).adapter()
EventEmitter = require(events).EventEmitter
oauth = require(oauth)
cronJob = require(cron).CronJob
class Plurk exntends Adapter
class PlurkStreaming exnteds EventEmitter

72

8. Hubot Plurk Adapter

Node.js
Class Twitter Adapter
Plurk Class Method run, send, reply
run
class Plurk entends Adapter
send: (plurk id, strings) ->
reply: (plurk id, strings) ->
run: ->

Plurk API
class PlurkStreaming extends EventEmitter
consuctor: (options) ->
plurk: (callback) ->
#
getChannel: ->
# Comet
reply: (plurk id, message) ->
#
acceptFriends: ->
#
get: (path, callback) ->
#GET
post: (path, body, callback)->
#POST
request: (method, path, body, callback)->
# OAuth
comet: (server, callback)->
# Comet JavaScript Callback JSON

constructor
constructor: (options) ->
super()

if options.key? and options.secret? and options.token? and options.token secret


@key = options.key
@secret = options.secret
@token = options.token
@token secret = options.token secret

8.3. Robot API

73

Node.js

# OAuth
@consumer = new oauth.OAuth(
http://www.plurk.com/OAuth/request token,
http://www.plurk.com/OAuth/access token,
@key,
@secret,
1.0,
http://www.plurk.com/OAuth/authorize.
HMAC-SHA1
)
@domain = www.plurk.com
# Comet
do @getChannel
else
throw new Error( Key, Secret, Token, Token Secret)

request method
request: (method, path, body, callback) ->
# Request
console.log(http://#{@domain}#{path})
# Callback

request = @consumer.get(http://#{@domain}#{path}, @token, @token secret, n


request.on response, (res) ->
res.on data, (chunk) ->
parseResponse(chunk+, callback)
res.on end, (data) ->
console.log End Request: #{path}
res.on error, (data) ->
console.log Error: + data
request.end()
#
parseResponse = (data, callback) ->
if data.length > 0
# Try/Catch JSON
try
callback null, JSON.parse(data)
catch err

74

8. Hubot Plurk Adapter

Node.js

console.log(Error Parse JSON: + data, err)


#
callback null, data || {}

Hubot Plurk Adapter


Lag Comet

Comet EventEmitter
comet: (server, callback) ->
# Callback
self = @
# Request
console.log([Comet] #{server})
Callback

request = @consumer.get(http://#{@domain}#{path}, @token, @token secret, null)


request.on response, (res) ->
res.on data, (chunk) ->
parseResponse(chunk+, callback)
res.on end, (data) ->
console.log End Request: #{path}
#
self.emit nextPlurk
res.on error, (data) ->
console.log Error: + data
request.end()
#
parseResponse = (data, callback) ->
if data.length > 0
# try/catch
try
# JavaScript Callback
data = data.match(/CometChannel.scriptCallback\((.+)\);\s*/)
jsonData =
if data?

8.3. Robot API

75

Node.js

jsonData = JSON.parse(data[1])
else
# Match parse
jsonData = JSON.parse(data)
catch err
console.log([Comet] Error:, data, err)
# Try/Catch JSON
try
# json data
callback null, jsonData.data
catch err
console.log([Comet]Error Parse JSON: + data, err)
#
callback null, data || {}

get post
get: (path, callback) ->
@request(GET, path, null, callback)
post: (path, body, callback) ->
@request(POST, path, body, callback)

Comet getChannel
getChannel: ->
self = @
@get /APP/Realtime/getUserChannel, (error, data) ->
if !error
# comet server
if data.comet server?
self.channel = data.comet server
# Channel Ready
self.emit(channel ready)

Plurk Adaper
send: (plruk id, strings)->
# Reply reply
@reply plurk id, strings

76

8. Hubot Plurk Adapter

Node.js

reply: (plurk id, strings) ->


strings.forEach (message) =>
@bot.reply(plruk id, message)

run
run: ->
self = @
options =
key: process.env.HUBOT PLURK KEY
secret: process.env.HUBOT PLURK SECRET
token: process.env.HUBOT PLURK TOKEN
token secret: process.env.HUBOT PLURK TOKEN SECRET
# API
bot = new PlurkStreaming(options)

# Twitter new Robot.TextMessage hubot-minecraft


r = @robot.constructor
#
@doPlurk = (data)->
#
if data.response?
data.content raw = data.response.content raw
data.user id = data.response.user id
# ID
if data.plurk id? and data.content raw
self.receive new r.TextMessage(data.plurk id, data.content raw)
# Comet Server Comet
bot.on channel ready, () ->
bot.plurk self.doPlurk
# Comet Polling
bot.on nextPlurk, ()->
bot.plurk self.doPlurk
#
do bot.acceptFriends
@bot = bot

8.3. Robot API

77

Node.js
AdapterHubot scripts
Adapter
[http://plurk.com/
elct9620 bot](http://plurk.com/elct9620 bot)

8.4
[ Hubot Adapter](http:// revo-skill.frost.tw/ blog/
2012/03/18/create-a-hubot-plurk-adapter/)

78

8. Hubot Plurk Adapter

Node.js

9.1 log.io
Real-time log monitoring in your browser
http://logio.org/
node.js (>=0.4.12 <=0.6.11)
npm config set unsafe-perm true
npm install -g --prefix=/usr/local log.io
log.io server start
http://localhost:8998

79

Node.js

80

9. Node.js

10

10.1 Express
NodeJS + Express GET/POST Request []
link2 []
link3 []

81

Node.js

82

10.

11

11.1 Node.js
Programming Node.js, April 2012 (est.), Travis Swicegood, Pragmatic Bookshelf
e Little Book on CoeeScript, January 2012, Alex MacCaw, OReilly Media
Node for Front-End Developers, January 2012, Garann Means, OReilly Media
Building Hypermedia APIs with HTML5 and Node, November 2011, Mike
Amundsen, OReilly Media
Node Web Development, August 2011, David Herron, PacktPub
CoeeScript: Accelerated JavaScript Development, July 2011, Trevor Burnham,
Pragmatic Bookshelf
Getting Started with GEO, CouchDB, and Node.js, July 2011, Mick ompson, OReilly Media
What Is Node?, July 2011, Brett McLaughlin, OReilly Media
Node: Up and Running, May 2011, Tom Hughes-Croucher, Mike Wilson,
OReilly Media

83

Node.js

Hands-on Node.js, e Node.js introduction and API reference, May 2011, Pedro Teixeira, LeanPub
e Node Beginner Book, Manuel Kiessling
Mastering Node.js, visionmedia

11.2 Node.js
e Node Sessions: e Best of OSCON 2011, August 2011, OReilly Media
(Video)
Tom Hughes-Croucher on Node, March 2011, OReilly Media (Video)

11.3 Node.js
Node Tuts

11.4 Node.js
Introduction To Node.js, Van Nguyen, CodeLesson

84

11.

You might also like