Created
December 23, 2011 16:42
-
-
Save jagoda/1514706 to your computer and use it in GitHub Desktop.
NodeJS wrapper to treat strings as streams.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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