Skip to content

Instantly share code, notes, and snippets.

@ikr
Created December 12, 2013 13:29
Show Gist options
  • Save ikr/7927934 to your computer and use it in GitHub Desktop.
Save ikr/7927934 to your computer and use it in GitHub Desktop.
Read stream out of a string. Needed for node.js < 0.10.0
(function () {
'use strict';
var util = require('util'),
Stream = require('stream');
/**
* A StringReader is paused by default. Only when resume() is called will it begin emitting
* events. It will do the following:
*
* - Emit the entire String or Buffer in the first (and only) data event.
* - Emit the end event, indicating that there is no more data.
* - Emit the close event, indicating that there's nothing more this reader will do.
*
* @see http://technosophos.com/2012/10/19/using-string-stream-reader-nodejs.html
*
* Under node 0.10+, use stream.Readable instead
* @see https://github.com/substack/stream-handbook#creating-a-readable-stream
*/
function StringReader(str) {
this.data = str;
}
util.inherits(StringReader, Stream);
module.exports = StringReader;
StringReader.prototype.open =
StringReader.prototype.resume = function () {
var that = this;
setTimeout(function () {
that.emit('data', that.data);
that.emit('end');
that.emit('close');
}, 0);
};
StringReader.prototype.pause = function () {};
StringReader.prototype.destroy = function () {
delete this.data;
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment