先来看一下上一篇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
");
- }).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