Skip to content

Instantly share code, notes, and snippets.

@gliese1337
Created June 23, 2011 23:54
Show Gist options
  • Save gliese1337/1043925 to your computer and use it in GitHub Desktop.
Save gliese1337/1043925 to your computer and use it in GitHub Desktop.
Wrapper to make a string or Buffer look like a Stream object.
function emit_string(obj,data,encoding){
obj.emit('data',(data instanceof Buffer
?data.toString(encoding)
:data[0])
);
}
function emit_buffer(obj,data){
obj.emit('data',(data instanceof Buffer
?data:new Buffer(data[0],data[1]))
);
}
function setEncoding(enc){
switch(enc){
case 'utf8':
case 'ascii':
case 'base64':
return this.encoding = enc;
default:
return this.encoding = null;
}
}
function resume(){
var i,l,encoder;
if(this.active) return;
this.active = true;
if(l=this.buffer.length-1){
encoder = this.encoding?emit_string:emit_buffer;
for(i=0;i<l;i++){encoder(this,this.buffer[i],this.encoding);}
if(this.buffer[i]===''){this.emit('end');this.destroy();}
else{encoder(this,this.buffer[i],encoding);}
this.buffer = [];
}
}
function write(data,enc){
if(this.active){
if(this.encoding){emit_string(this,data,enc||this.encoding);}
else{emit_buffer(this,data);}
}else{
this.buffer.push(data instanceof Buffer
?data:[data,enc||this.encoding]);
}
return true;
}
function end(){
if(arguments.length){this.write.apply(this,arguments);}
if(this.active){this.emit('end');this.destroy();}
else{this.buffer.push('');}
this.readable = false;
}
function nop(){}
function MemoryStream(i_data,opts){
var mdata;
if(this === (function(){return this;}())){
new MemoryStream(i_data,opts);
}
function gen_mdata(){
this.readable=true;
this.writable=opts && !opts.readonly;
this.encoding=null;
this.active=false;
this.buffer=i_data
?[typeof i_data === 'string'?[i_data,(opts && opts.encoding)||'utf8']:i_data]:[]
}
gen_mdata.prototype = this;
mdata = new gen_mdata;
Object.defineProperty(this,"readable",{get:function(){return mdata.readable;},enumerable:true});
Object.defineProperty(this,"writable",{get:function(){return mdata.writable;},enumerable:true});
this.setEncoding = setEncoding.bind(mdata);
this.pause = function(){mdata.active=false;};
this.resume = resume.bind(mdata);
this.end = end.bind(mdata);
this.destroy = function(){
mdata.active = false;
this.write = this.destroy = this.resume = nop;
};
if(!mdata.writable){
this.write = nop;
mdata.buffer.push('');
}else{
this.write = write.bind(mdata);
}
}
MemoryStream.prototype = new process.EventEmitter;
MemoryStream.prototype.pipe = require('stream').Stream.prototype.pipe;
exports.MemoryStream = MemoryStream;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment