先來看一下上一篇hello world的例子 http://www.linuxidc.com/Linux/2012-02/53534.htm
[javascript]
- var http = require('http');
- http.createServer(function (req, res) {
- res.writeHead(200, {'Content-Type': 'text/plain'});
- res.end('Hello World\n');
- }).listen(1337, "127.0.0.1");
- console.log('Server running at http://127.0.0.1:1337/');
了解javascript的話,代碼基本能看懂,不過代碼中出現的object和function沒有見過.先別急著用搜索引擎,先看一下 http://nodejs.org/ 的官方文檔.
點擊 v0.6.5 docs 進入 http://nodejs.org/docs/v0.6.5/api/
文檔已經分好了類,不好直接搜索,還好它有一個 View on single page 的鏈接,點擊以後搜索.
搜索第一個出現的函數 require 它在Globals之下,它是一個全局的 function, 官方說明如下:require() :To require modules. See the Modules section. 查看Modules小節,了解到module 就是node.js的包管理機制,有點類似於python.require('http') 是加載了HTTP module.
發現console 也在Globals之下,它是一個全局的 object, 官方說明如下:console:Used to print to stdout and stderr. See the stdio section. 查看 stdio小節,了解到console就是標准io類似java的systen.out.
按這樣看,其他相關說明應該都在http小節,查看一下,的確如此.
查看http的整個API,包含幾類成員,有 object ,function,property,event. 前三種定義方式,遵照javascript語法,各種javascript基本都一樣,那node.js是這麼定義的,查看Events小節,添加監聽使用如下方式:
emitter.addListener(event, listener)
emitter.on(event, listener)
[javascript]
- server.on('connection', function (stream) {
- console.log('someone connected!');
- });
http.createServer 官方說明如下:
http.createServer([requestListener])Returns a new web server object.
The requestListener is a function which is automatically added to the 'request' event.
Event: 'request'function (request, response) { }
Emitted each time there is a request. Note that there may be multiple requests per connection (in the case of keep-alive connections). request is an instance of http.ServerRequest and response is an instance ofhttp.ServerResponse
根據以上API可以推算以下兩種代碼是一致的
[javascript]
- http.createServer(function (req, res) {
- })
[javascript]
- var server = http.createServer();
- server.on('request',function (req, res){
- })
修改hello world源代碼,測試結果的卻如此.
hello world中還用到了以下函數:
response.writeHead(statusCode, [reasonPhrase], [headers])
response.end([data], [encoding]) The method, response.end(), MUST be called on each response.
server.listen(port, [hostname], [callback])
通過對hello world 源碼的分析,基本上了解了node.js 的結構,可以看出 node.js是基於事件的JavaScript,可以開發基於事件的Web應用.
下篇講node,js 接收get post請求 http://www.linuxidc.com/Linux/2012-02/53536.htm