这是我的功能
function postRequest(requestData, returnData) {
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = require('http').request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
returnData(chunk);
});
});
req.on('error', function(e) {
returnData(e.message);
});
// write data to request body
req.write(requestData);
req.end();
}
正如您所知,回调函数将返回错误消息,或者它将返回响应数据。
我想创建两个自定义事件监听器 第一个是.on(' responseError'),第二个是.on(' responseData')
我希望能够致电
postRequest.on('responseError', function(err){/*Do something*/});
以及
postRequest.on('responseData', function(data){/*Do something else*/});
如何使用节点require('events').EventEmitter
?
答案 0 :(得分:1)
几个小时之后(我是面向对象的javascript的新手)我做到了,这就是解决方案
//import utils because it is easier to do inheritance
var util = require("util")
//import core events
, EventEmitter = require("events").EventEmitter;
var ComUtils = function() {
//add events to class constructor
EventEmitter.call(this);
}
//inherit from events
util.inherits(ComUtils, EventEmitter);
//add postRequest function to ComUtils class
ComUtils.prototype.postRequest = function(dest, requestJSON) {
//make a reference to postRequest function(important)
var self = this;
var options = {
hostname: 'www.google.com',
port: 80,
path: dest,
method: 'POST'
};
var req = require('http').request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
//create an emitter(from EventEmitter class) that will fire off an event
self.emit('returnData',chunk);
});
});
req.on('error', function(e) {
//another emitter
self.emit('error',e.message);
});
// write data to request body
req.write(requestJSON);
req.end();
}
module.exports.ComUtils = ComUtils;
要使用此功能,需要执行以下操作
var httpUtils = require('./someModule')
, utils = new httpUtils.ComUtils();
utils.on('returnData', function(data){
console.log(data)
}).postRequest('/', 'requestJSON');