我正在尝试创建一个行为类似net.createServer
的函数,除了它返回的是套接字周围的包装器而不是套接字。
(这些要点是进行自动数据转换。)
我的最新尝试如下:
var net = require('net');
var util = require('util');
var stream = require('stream');
var EventEmitter = process.EventEmitter;
exports.createServer = createServer;
function createServer(arg0, arg1) {
var server;
var netServer;
var ocb;
if (typeof arg1 === 'function') {
// options, callback
netServer = net.createServer(arg0, callback);
ocb = arg1;
} else if (typeof arg0 === 'function') {
// callback
netServer = net.createServer(callback);
ocb = arg0;
} else {
// options?
netServer = net.createServer(arg0);
ocb = null;
}
server = new Server(netServer);
function callback(socket) {
ocb(new LiftedSocket(socket));
};
return server;
;
}
function Server(netServer) {
this.netServer = netServer;
}
util.inherits(Server, EventEmitter);
Server.prototype.listen = function() {
this.netServer.listen.apply(this.netServer, arguments);
}
function LiftedSocket(socket) {
stream.Duplex(this);
this.socket = socket;
}
util.inherits(LiftedSocket, stream.Duplex);
LiftedSocket.prototype._read = function(size) {
console.log('_read', size);
// transforming code goes here
this.socket.read(size);
}
LiftedSocket.prototype._write = function(chunk, encoding, callback) {
console.log('_write', chunk, encoding, callback);
// transforming code goes here
this.socket.write(chunk, callback);
}
但是在测试时(通过尝试从返回的LiftedSocket
进行管道传输),它失败并出现错误,包括:
Uncaught TypeError: Cannot read property 'pipesCount' of undefined
at LiftedSocket.Readable.pipe (_stream_readable.js:453:16)
Uncaught TypeError: Cannot read property 'flowing' of undefined
at LiftedSocket.Readable.on (_stream_readable.js:691:44)
我希望在构建LiftedSocket
时我做错了什么,但我想不出来。
答案 0 :(得分:1)
我错误地调用了超类构造函数。应该是:
stream.Duplex.call(this, {})