util.inherits(constructor,superConstructor)是一个实现对象间原型继承的函数。
var util = require('util');
function Base() {
this.name = 'base';
this.base = 1989;
this.sayHello = function() {
console.log('Hello ' + this.name);
};
}
Base.prototype.showName = function() {
console.log(this.name);
};
function Sub() {
this.name = 'sub';
}
util.inherits(Sub, Base);
var objBase = new Base();
objBase.showName();
objBase.sayHello();
console.log(objBase);
var objSub = new Sub();
objSub.showName();
//objSub.sayHello();
console.log(objSub);
/*
运行结果:
base
Hello base
{ name: 'base', base: 1991, sayHello: [Function] }
sub
{ name: 'sub' }
*/
Sub仅仅继承了Base在原型中定义的函数,而构造函数内部创造的base属性和sayHello函数都没有被Sub继承。同时,在原型中定义的属性不会被console.log作为对象的属性输出。var util = require('util');
function Person() {
this.name = 'ichenxiaodao';
this.toString = function() {
return this.name;
};
}
var obj = new Person();
console.log(util.inspect(obj));
console.log(util.inspect(obj, true));
/*
运行结果:
{ name: 'ichenxiaodao', toString: [Function] }
{ name: 'ichenxiaodao',
toString:
{ [Function]
[length]: 0,
[name]: '',
[arguments]: null,
[caller]: null,
[prototype]: { [constructor]: [Circular] } } }
*/
除了以上我们介绍的几个函数之外,util还提供了util.isArray()、util.isRegExp()、util.isDate()、util.isError()四个类型测试工具,以及util.format()、util.debug()等工具。有兴趣的读者可以访问http://nodejs.org/api/util.html了解详细内容。
var events = require('events');
var emitter = new events.EventEmitter();
//注册事件
//指定事件注册一个监听器,接受一个字符串event和一个回调函数listener。
emitter.on("someEvent", function(arg1, arg2) {
console.log("listener1", arg1, arg2);
});
//注册事件
emitter.on("someEvent", function(arg1, arg2) {
console.log("listener2", arg1, arg2);
});
//发射事件
//发射event事件,传递若干可选参数到事件监听器的参数表。
emitter.emit("someEvent", "ichenxiaodao", 1989);
/*
运行结果:
listener1 ichenxiaodao 1989
listener2 ichenxiaodao 1989
*/EventEmitter.once(event,listener)为指定事件注册一个单次监听器,即监听器最多只会触发一次,触发后立刻解除该监听器。var events = require('events');
var emitter = new events.EventEmitter();
emitter.emit('error');
/*
运行结果:
events.js:74
throw TypeError('Uncaught, unspecified "error" event.');
^
TypeError: Uncaught, unspecified "error" event.
at TypeError (<anonymous>)
at EventEmitter.emit (events.js:74:15)
at Object.<anonymous> (/Users/cdz/workspace/my-node/NodeJS_Dev_Guide_Book/4/error.js:5:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
*/大多数时候我们不会直接使用EventEmitter,而是在对象中继承它。包括fs、net、http在内的,只要是支持事件响应的核心模块都是EventEmitter的子类。var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.write('<h1>Node.js</h1>');
res.end('<p>Hello World</p>');
}).listen(3000);
console.log("HTTP server is listening at port 3000.");http.createServer创建了一个http.Server的实例,将一个函数作为HTTP请求处理函数。这个函数接受两个参数,分别是请求对象(req)和响应对象(res)。var http = require('http');
var server = new http.Server();
server.on('request', function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.write('<h1>Node.js</h1>');
res.end('<p>Hello World</p>');
});
server.listen(3000);
console.log("HTTP server is listening at port 3000.");http.ServerRequest是HTTP请求的信息,是后端开发者最关注的内容。它一般由var http = require('http');
var url = require('url');
var util = require('util');
http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end(util.inspect(url.parse(req.url, true)));
}).listen(3000);
/*
访问:
http://127.0.0.1:3000/user?name=ichenxiaodao&email=ichenxiaodao@gmail.com
返回:
{ protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?name=ichenxiaodao&email=ichenxiaodao@gmail.com',
query: { name: 'ichenxiaodao', email: 'ichenxiaodao@gmail.com' },
pathname: '/user',
path: '/user?name=ichenxiaodao&email=ichenxiaodao@gmail.com',
href: '/user?name=ichenxiaodao&email=ichenxiaodao@gmail.com'
}
*/手动解析POST请求体。var http = require('http');
var querystring = require('querystring');
var util = require('util');
http.createServer(function(req, res) {
var post = '';
req.on('data', function(chunk) {
post += chunk;
});
req.on('end', function(chunk) {
post = querystring.parse(post);
res.end(util.inspect(post));
});
}).listen(3000);http.ServerResponse是返回给客户端的信息,决定了用户最终能看到的结果。它也是由http.Server的request事件发送的,作为第二个参数传递,一般简称为response或res。var http = require('http');
var querystring = require('querystring');
var contents = querystring.stringify({
name: "ichenxiaodao",
email: "ichenxiaodao@gmail.com",
address: "Shanghai"
});
var options = {
host: "www.byvoid.com",
path: "/application/node/post.php",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": contents.length
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf-8');
res.on('data', function(data) {
console.log(data);
});
});
req.write(contents);
req.end();http.get(options,callback)http模块还提供了一个更加简便的方法用于处理GET请求:http.get。它是http.request的简化版,唯一的区别在于http.get自动将请求方法设为了GET请求,同时不需要手动调用req.end()。拓展阅读:http://nodejs.org/api/index.html
文档信息
原文地址:http://blog.csdn.net/cdztop/article/details/33473299