Skip to content

Instantly share code, notes, and snippets.

@FGRibreau
Created November 2, 2013 22:56
Show Gist options
  • Save FGRibreau/7284395 to your computer and use it in GitHub Desktop.
Save FGRibreau/7284395 to your computer and use it in GitHub Desktop.
Mock NodeJS net.Socket with ReadWriteStream
var dummySocket = new ReadWriteNetStream();

// Debug
dummySocket.on('data', function(data){
console.log('write received', data);
});

dummySocket.write('hey !');
var ReadWriteStream = require('./ReadWriteStream')
, events = require('events')
, util = require('util')
, _ = require('lodash');
function ReadWriteNetStream(specialTimeout){
this.specialTimeout = specialTimeout || false;
ReadWriteStream.call(this);
this.bufferSize = 0;
this.remoteAddress = '';
this.remotePort = '';
this.bytesRead = '';
this.bytesWritten = '';
}
util.inherits(ReadWriteNetStream, ReadWriteStream);
// Net.Socket
[
'connect'
, 'setSecure'
, 'setTimeout'
, 'setNoDelay'
, 'setKeepAlive'
, 'address'
, 'timeout'
].forEach(function(funcName){
ReadWriteNetStream.prototype[funcName.name || funcName] = (function(func){
var event = funcName.event || func;
return function(a, b){
if(this.specialTimeout && funcName === 'setTimeout' && _.isFunction(b)){
this.on('timeout', b);
}
var args = Array.prototype.slice.call(arguments);
args.unshift(event);
this.emit.apply(this, args);
};
}(funcName));
});
module.exports = ReadWriteNetStream;
var events = require('events'),
util = require('util');
function ReadWriteStream() {
events.EventEmitter.call(this);
this.readable = true;
this.writable = true;
}
util.inherits(ReadWriteStream, events.EventEmitter);
// Each of these methods just triggers an event with the same name and calling parameters
[
// Readable Stream
// 'data' is only an event triggered by .write()
'end'
, 'error'
, 'close'
, 'setEncoding'
, 'pause'
, 'resume'
, 'destroy'
//, 'pipe' // currently not supported, inherit from Stream if you want this
// Writable Stream
, 'drain'
//, 'error'
//, 'close'
//, 'pipe'
, {name:'write',event:'data'}
, 'destroySoon'
].forEach(function(func){
ReadWriteStream.prototype[func.name || func] = (function(func){
var event = func.event || func;
return function(){
var args = Array.prototype.slice.call(arguments);
args.unshift(event);
this.emit.apply(this, args);
};
}(func));
});
module.exports = ReadWriteStream;
@thiagodelgado111
Copy link

great idea! it will be very helpfull! thanks for sharing it! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment