data-stream.js 1.2 KB

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