7. 慣C自幹Web Server
要先喀完
RFC2616
Hypertext Transfer Protocol -- HTTP/1.1
http://www.w3.org/Protocols/rfc2616/rfc2616.html
所以我就放棄這麼做了!
8. 直到有一天,我遇見Node.js
這樣就是一個Web Server !!!
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
9. Wiki Node.js
Node.js is a packaged compilation of Google's
V8 JavaScript engine.
Node.js is a server-side software system
designed for writing scalable Internet
applications, notably web servers. Programs
are written on the server side in JavaScript,
using event-driven, asynchronous I/O to
minimize overhead and maximize scalability.
13. 一個簡單的Web Server by Node.js
var http = require("http"); 宣告要使用http模組
建立一HTTP Server
http.createServer( function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end(); Callback Function
}).listen(8888);
要該HTTP Server監聽8888 port
21. Callback function for event-driven
var http = require("http");
定義Callback function for request event
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
將onRequest註冊至request event
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
22. Event in Node.js → Interrupt of chip
Is that right?????
Understanding the node.js
event loop
23. Arguments of the callback function
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
request: instance of http.IncomingMessage
response: instance of http.ServerResponse
http://nodejs.org/api/http.html#http_event_request
24. Module
將HTTP Server相關的code包裝
var http = require("http");
function onRequest(request, response) {
console.log("Request received.");
response.end("Hello World");
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
25. mylib.js
function foo(port) {
var http = require("http");
function onRequest(request, response) {
console.log("Request received.");
response.end("Hello World");
}
http.createServer(onRequest).listen(port);
console.log("Server has started.");
}
exports.onRequest = foo;
26. server.js
var server = require("./mylib");
var linstening_port = 8888;
server.onRequest(linstening_port);