data-stream.js
1 /*global module, process*/ 2 var Buffer = require('safe-buffer').Buffer; 3 var Stream = require('stream'); 4 var util = require('util'); 5 6 function DataStream(data) { 7 this.buffer = null; 8 this.writable = true; 9 this.readable = true; 10 11 // No input 12 if (!data) { 13 this.buffer = Buffer.alloc(0); 14 return this; 15 } 16 17 // Stream 18 if (typeof data.pipe === 'function') { 19 this.buffer = Buffer.alloc(0); 20 data.pipe(this); 21 return this; 22 } 23 24 // Buffer or String 25 // or Object (assumedly a passworded key) 26 if (data.length || typeof data === 'object') { 27 this.buffer = data; 28 this.writable = false; 29 process.nextTick(function () { 30 this.emit('end', data); 31 this.readable = false; 32 this.emit('close'); 33 }.bind(this)); 34 return this; 35 } 36 37 throw new TypeError('Unexpected data type ('+ typeof data + ')'); 38 } 39 util.inherits(DataStream, Stream); 40 41 DataStream.prototype.write = function write(data) { 42 this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); 43 this.emit('data', data); 44 }; 45 46 DataStream.prototype.end = function end(data) { 47 if (data) 48 this.write(data); 49 this.emit('end', data); 50 this.emit('close'); 51 this.writable = false; 52 this.readable = false; 53 }; 54 55 module.exports = DataStream;