'use strict' ; import { Readable , Stream } from 'stream' ; param val returns export function IsStream ( val ) { return ( typeof val == 'object' && typeof val . pipe == 'function' ) ; } param val returns export function IsReadableStream ( val ) { return ( IsStream ( val ) && typeof val . read === 'function' ) ; } param stream returns async export function StreamToBuffer ( stream ) { return new Promise ( ( resolve , reject ) => { const buffersCache = [ ] ; stream . on ( 'data' , ( data ) => { buffersCache . push ( data ) ; } ) ; stream . on ( 'end' , ( ) => { resolve ( Buffer . concat ( buffersCache ) ) ; } ) ; stream . on ( 'error' , ( error ) => { reject ( error ) ; } ) ; } ) ; } param stream param encoding returns async export function StreamToString ( stream , encoding ? ) { return StreamToBuffer ( stream ) . then ( ( buffer ) => { return buffer . toString ( encoding || 'utf8' ) ; } ) ; } param stream param size param peek returns async export function ReadChunkFromStream ( stream , size , peek ? ) { if ( ! stream || ! IsReadableStream ( stream ) ) { throw Error ( 'Argument stream must be a Readable Stream' ) ; } stream . pause ( ) ; return new Promise ( ( resolve , reject ) => { const errorEvent = ( err ) => { reject ( err ) ; } ; const readableEvent = ( ) => { const data = stream . read ( size ) ; if ( data ) { if ( peek ) { stream . unshift ( data ) ; } stream . removeListener ( 'error' , errorEvent ) ; resolve ( data ) ; } else { stream . once ( 'readable' , readableEvent ) ; } } ; stream . once ( 'readable' , readableEvent ) ; stream . on ( 'error' , errorEvent ) ; } ) ; }