Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Require the core node modules.
- var stream = require( "stream" );
- var util = require( "util" );
- var crypto = require( "crypto" );
- var fileSystem = require( "fs" );
- // ----------------------------------------------------------------------------------- //
- // ----------------------------------------------------------------------------------- //
- // CAUTION: Run the code in the next tick to give the full prototype chain a chance to
- // initialize. If we try to run immediately, we'll get the function hoisting for the
- // ETagStream constructor, but the prototype chain will not yet be defined fully.
- process.nextTick(
- function run() {
- var fileReadStream = fileSystem.createReadStream( "./gina-carano.jpg" );
- // Once the file is finished piping into the etagStream, it will emit an etag
- // event with the computed MD5 hash.
- var etagStream = new ETagStream()
- .on(
- "etag",
- function handleETag( etag ) {
- console.log( "ETag:", etag );
- }
- )
- ;
- fileReadStream.pipe( etagStream );
- }
- );
- // ----------------------------------------------------------------------------------- //
- // ----------------------------------------------------------------------------------- //
- // I provide a writable stream that will emit an "etag" event once the stream is closed.
- // The etag will be an MD5 hash of the content that was written to the stream.
- // --
- // NOTE: In this version, we'll be using the "legacy" methods of the underlying Hash
- // object which allow for intuitive .update() and .digest() methods.
- function ETagStream() {
- // Call the super constructor.
- stream.Writable.call( this );
- this._hasher = crypto.createHash( "md5" );
- // Listen for the "finish" event, which will indicate that we have all the data that
- // we need in order to generate the MD5 has of the stream content.
- this.once( "finish", this._handleFinish.bind( this ) );
- }
- util.inherits( ETagStream, stream.Writable );
- // ---
- // PRIVATE METHODS.
- // ---
- // I handle the finish event, which, in turn, emits an "etag" event.
- ETagStream.prototype._handleFinish = function() {
- // When dealing with "legacy" crypto methods, all we have to do is digest all of
- // the data that has been aggregated in the _write() method.
- this.emit( "etag", this._hasher.digest( "hex" ) );
- };
- // I write data to the etag stream.
- ETagStream.prototype._write = function( chunk, encoding, writeComplete ) {
- // When dealing with "legacy" crypto methods, we can simply pass the chunk into
- // the underlying hash without giving any concern to back-pressure.
- this._hasher.update( chunk, encoding );
- writeComplete();
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement