Skip to content

Instantly share code, notes, and snippets.

@jagoda
Created December 23, 2011 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jagoda/1514706 to your computer and use it in GitHub Desktop.
Save jagoda/1514706 to your computer and use it in GitHub Desktop.
NodeJS wrapper to treat strings as streams.
var events = require('events');
var util = require('util');
function FixedStream (string) {
events.EventEmitter.call(this);
this._buffer = new Buffer(string);
this._data = [];
this._end = false;
}
util.inherits(FixedStream, events.EventEmitter);
FixedStream.prototype.readable = true;
FixedStream.prototype.emit = function (evt) {
if (!this._end && evt === 'end') {
this._end = true;
}
if (this._end && evt === 'data') {
throw new Error('Stream has already ended.');
}
return events.EventEmitter.prototype.emit.apply(this, arguments);
};
FixedStream.prototype.on = function (evt, listener) {
events.EventEmitter.prototype.on.apply(this, arguments);
if (evt === 'data') {
this.emit('data', this._getData());
this.emit('end');
}
else if (evt === 'end') {
if (this._end) {
listener();
}
}
};
FixedStream.prototype.setEncoding = function (encoding) {
this._encoding = encoding;
};
FixedStream.prototype._getData = function () {
return this._encoding ? this._buffer.toString(this._encoding) :
this._buffer;
};
var crypto = require('crypto');
var utilities = require('../utilities');
function id (value, callback) {
if (utilities.isString(value)) {
return id(new utilities.FixedStream(value), callback);
}
if (!utilities.isStream(value)) {
throw new Error('[id] expects stream.');
}
var shasum = crypto.createHash('sha1');
var hash;
value.on('data', function (data) { shasum.update(data); });
value.on('end', function () {
hash = shasum.digest('hex');
if (utilities.isFunction(callback)) {
callback(hash);
}
});
return hash;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment