Node.js入门(二)

一、事件

所有产生Node.js事件的对象都是 events.EventEmitter 的实例,即:

//event.js

var EventEmitter = require(‘events‘).EventEmitter;

var event = new EventEmitter();

event.on(‘some_event‘,function (){  //注册事件some_event的一个监听器

  console.log(‘some_event occured.‘);

});

setTimeout(function (){

  event.emit(‘some_event‘);  //发送事件

},1000);

 

EventEmitter示例:

var events = require(‘events‘);  //引入events模块
var emitter = new events.EventEmitter();

emitter.on(‘someEvent‘,function (arg1,arg2){    //事件监听器
  console.log(‘listener1‘,arg1,arg2);
});
emitter.on(‘someEvent‘,function (arg1,arg2){    //另一个事件监听器
  console.log(‘listener2‘,arg1,arg2);
});
emitter.emit(‘someEvent‘,‘liuqiuchen‘,‘27‘);    //事件发射,注册到这个事件的事件监听器被依次调用

 

EventEmitter常用API:

*emitter.on(event,listener);
*emitter.addListener(event,listener);
*为指定事件注册一个监听器,接收一个字符串event和一个回调函数listener
*
*emitter.emit(event,[arg1],[arg2],[...]);发射event事件
*
*emitter.once(event,listener);为事件注册一个单次监听器,即监听器最多只会触发一次,触发后立刻解除该监听器
*
*emitter.removeListener(event,listener);移除指定事件的某个监听器,listener必须是该事件已经注册过的监听器
*
*emitter.removeAllListeners([event]);移除所有事件的所有监听器,如果指定event,则移除指定事件的所有监听器。

测试代码:

emitter.on(‘connection‘,function (stream){
  console.log(‘someone connected!‘);
});
emitter.emit(‘connection‘);

emitter.addListener(‘addListener‘,function (name,age){
  console.log(name + age);
});
emitter.emit(‘addListener‘,‘YourName‘,27);

emitter.once(‘only_once_event‘,function (){
  console.log(‘only_once‘);
})
emitter.emit(‘only_once_event‘);

var callback1 = function (stream){
  console.log(‘person1 connected‘);
};
var callback2 = function (stream){
  console.log(‘person2 connected‘);
};
emitter.on(‘connection‘,callback1);
emitter.on(‘connection‘,callback2);
//emitter.emit(‘connection‘);
emitter.removeListener(‘connection‘,callback1);
//emitter.emit(‘connection‘);
emitter.removeAllListeners(‘connection‘);
emitter.emit(‘connection‘);

 

error事件
我们在遇到异常的时候通常会发射error事件

var events = require(‘events‘);
var emitter = new events.EventEmitter();
emitter.emit(‘error‘);

 

二、函数

1 function execute(someFunction,value){
2   someFunction(value);
3 }
4 
5 function say(word){
6   console.log(word);
7 }
8 
9 execute(say,‘Hello‘);

 

匿名函数:

1 function execute(someFunction,value){
2   someFunction(value);
3 }
4 execute(function (word){console.log(word)},‘Hello‘);

 

函数传递是如何让HTTP服务器工作的

1 var http = require(‘http‘);
2 
3 http.createServer(function (request,response){      //我们向createServer()函数传递了一个匿名函数
4   response.writeHead(200,{‘Content-Type‘:‘text/plain‘});
5   response.write(‘Hello World‘);
6   response.end();
7 }).listen(8888);

 

同下:

 

1 var http = require(‘http‘);
2 http.createServer(onRequest).listen(8888);
3 
4 function onRequest(request,response){
5   response.writeHead(200,{‘Content-Type‘:‘text/plain‘});
6   response.write(‘Hello world‘);
7   response.end();
8 }

 

 

三、路由(URL)

url.parse(string).query
                                           |
           url.parse(string).pathname      |
                       |                   |
                       |                   |
                     ------ -------------------
http://localhost:8888/start?foo=bar&hello=world
                                ---       -----
                                 |          |
                                 |          |
              querystring(string)["foo"]    |
                                            |
                         querystring(string)["hello"]

详见:http://nodeapi.ucdok.com/#/api/url.html

 

创建两个模块的公开接口

1 //router.js
2 
3 function route(pathname){
4   console.log(‘About to route a request for ‘ + pathname);
5 }
6 
7 exports.route = route;    //模块公开的接口

 

 1 //server.js
 2 
 3 var http = require(‘http‘);
 4 var url = require(‘url‘);
 5 
 6 function start(route){
 7   function onRequest(request,response){
 8 
 9   var pathname = url.parse(request.url).pathname;
10   route(pathname);
11 
12   response.writeHead(200,{‘Content-Type‘:‘text/plain‘});
13   response.write(‘Hello world‘);
14   response.end();
15   }
16 
17   http.createServer(onRequest).listen(8888);
18   console.log(‘Server has started‘);
19 }
20 
21 exports.start = start;

 

1 //调用文件index.js
2 
3 var server = require(‘./server‘);
4 var router = require(‘./router‘);
5 
6 //server.start(router.route);    //Server has started
7 server.start(router.route(‘http://www.baidu.com‘));    //About to route a request for http://www.baidu.com

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。