Wrapping NodeJS's net.createServer into a producer of customised sockets-Collection of common programming errors

I’m trying to make a function which behaves like net.createServer, except that it returns objects which are wrappers around sockets, instead of sockets.

(The point of these will be to do automatic data conversion.)

My latest attempt looks like:

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);
}

But when tested (by trying to pipe from a returned LiftedSocket) it fails with errors including:

 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)

I expect I’m doing something wrong when constructing the LiftedSocket, but I can’t think what.

  1. I had called the superclass constructor incorrectly. It should have been:

    stream.Duplex.call(this, {})
    

Originally posted 2013-11-19 13:18:00.