Professional Documents
Culture Documents
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
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
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
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
nodeJS
nodeJS.tw javascript
CoeeScript
Node.js
Node.js
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
Node.js
event loop
I/O render, re ow
instance NodeJS
event loop
process.nextTick
event loop
alert() Javascript timer
delay alert
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
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
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)
server.on(init,
require(./ tools).cookieParser);
server.listen(8080,
127.0.0.1);
cookieParser nodeunit
{ Cookie:
15
Node.js
}, normal case: function(test) {
test.expect(1);
var
obj
tools).cookieParser(this.request,
require(./
this.response);
<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) {
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>
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
https://github.com/caolan/async
24
2. JavaScript NodeJS
Node.js
25
Node.js
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
= 127.0.0.1,
port = 1337,
http = require(http);
server = http.createServer(function (req, res) {
29
Node.js
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
console
javascript console node.js
(debug) console
console.log(Server running at http:// + ip + : + port);
30
4. Node.js
Node.js
node.js
http://127.0.0.1:1337/test
/test /favicon.ico/test
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);
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
33
Node.js
4.3 node.js
rount
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
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
error
error true error
false content content
4.3. node.js
35
Node.js
<!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
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. 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);
= 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();
});
39
Node.js
server.listen(port, ip);
console.log(Server running at http:// + ip + : + port);
node.js
4.6
http
http
node.js
javascript node.js
node.js
40
4. Node.js
NPM
npm
5.1 NPM
Node.js 0.6.3 npm
npm
npm -v
41
Node.js
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
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
5.1. NPM
43
Node.js
MacPorts
MacPorts OS X 10.6
10.7
http://www.macports.org/
npm
sudo port install 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
global
npm node modules
C:\Program Files\nodejs\node modules
46
5. NPM
Node.js
local
node modules .bin .bin PATH
global
Windows 7 2008
npm Administrator
5.2. NPM
47
Node.js
5.3
search install npm
commands
npm help
npm help
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 update
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
:number
req.params.number url
/user/:id/user/xxx
req.params.id xxx
express
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);
middleware app.use
responserequestnext
next middleware
localhost:1337/
middleware app.use
middleware url
app.get middleware app.get
request, response, next
next
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.all
app.get
/
user/0 app.all next /
user/:id /user/0/edit /
user/:id/edit
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>
}
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;
59
Node.js
node.js GET
qs
= require(querystring),
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 <
qs.parse querystring
{username=wordsmith&email=wordsmith%40some.where}
user GET
response user.username user.email
= require(url),
fs
= require(fs),
qs
= require(querystring),
server;
server = http.createServer(function (req,res) {
var urlData,
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);
62
6. Express
Node.js
HTML
HTML
<!DOCTYPE html>
<html>
<head>
<title>Node.js (3)</title>
<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>
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);
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;
65
Node.js
= 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
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
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:
}
}
72
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()
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
74
Node.js
Comet EventEmitter
comet: (server, callback) ->
# Callback
self = @
# Request
console.log([Comet] #{server})
Callback
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
Node.js
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)
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
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.