All files index.ts

100% Statements 28/28
100% Branches 8/8
100% Functions 6/6
100% Lines 28/28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78    2x                           2x           12x   12x 12x   12x 12x 12x       16x 6x 10x 10x 10x         10x         10x   8x 8x   8x 6x   8x       2x 2x           10x 10x 4x 10x     12x   12x      
'use strict'
 
import * as through2 from 'through2'
 
 
export interface HeadResult
{
	head: Buffer;
	stream: NodeJS.ReadableStream;
}
 
export interface Options
{
	bytes: number;
}
 
export default function(
	readable: NodeJS.ReadableStream,
	opts: Options
)
: Promise< HeadResult >
{
	return new Promise< HeadResult >( ( resolve, reject ) =>
	{
		const headStream = through2( onChunk, onEnd );
		const outputStream = through2( );
 
		let bytesRead = 0;
		let isComplete = false;
		const chunks: Array< Buffer > = [ ];
 
		function complete( )
		{
			if ( isComplete )
				return null;
			isComplete = true;
			const head = Buffer.concat( chunks );
			resolve( {
				head,
				stream: outputStream,
			} );
 
			return head;
		}
 
		function onChunk( chunk, encoding, callback )
		{
			if ( !isComplete )
			{
				chunks.push( chunk );
				bytesRead += chunk.length;
 
				if ( bytesRead >= opts.bytes )
					this.push( complete( ) );
 
				return callback( );
			}
			else
			{
				this.push( chunk );
				return callback( );
			}
		}
 
		function onEnd( callback )
		{
			const head = complete( );
			if ( head )
				this.push( head );
			return callback( );
		}
 
		headStream.once( 'error', reject );
 
		readable.pipe( headStream ).pipe( outputStream );
	} );
}