手机版
你好,游客 登录 注册
背景:
阅读新闻

node.js 分析hello world的例子

[日期:2012-02-06] 来源:Linux社区  作者:dellheng [字体:大 中 小]

先来看一下上一篇hello world的例子 http://www.linuxidc.com/Linux/2012-02/53534.htm

[Javascript]
  1. var http = require('http');  
  2. http.createServer(function (req, res) {  
  3.   res.writeHead(200, {'Content-Type': 'text/plain'});  
  4.   res.end('Hello World\n');  
  5. }).listen(1337, "127.0.0.1");  
  6. 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]
  1. server.on('connection', function (stream) {  
  2.   console.log('someone connected!');  
  3. });  


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]
  1. http.createServer(function (req, res) {  
  2. })  
[javascript]
  1. var server = http.createServer();  
  2. server.on('request',function (req, res){  
  3. })  
修改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
linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款