1.1.1 • Published 5 years ago
@latel88/stream v1.1.1
Stream
how to use
- install
npm install @latel88/stream
- CJS
const { Stream, Pipe } = require( "@latel88/stream" ).default;
- ESM
import { Stream, Pipe } from "@latel88/stream";
exsample
- how to use stream class.
class FileStream extends Stream
{
constructor ( src, type = "text" )
{
super( ( resolve, reject ) =>
{
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () =>
{
if (xhr.readyState === 4)
{
if ((200 <= xhr.status && xhr.status < 300) || (xhr.status === 304))
{
const source = xhr.response;
resolve( source );
}
else
{
reject( new Error( `File not found. ${ url }` ) );
}
}
};
xhr.onerror = () =>
{
reject( new Error( `File not found. ${ url }` ) );
};
xhr.open( "GET", src, true );
xhr.responseType = type;
xhr.send( null );
} );
}
}
- how to use pipe class.
class ToImagePipe extends Pipe
{
constructor ()
{
super( ( data, resolve, reject ) =>
{
const source = new Image();
source.onload = () => resolve( source );
source.onerror = () => reject( new Error( "Can not process image." ) );
switch (true)
{
case typeof( data.source ) === "string":
source.src = `data:image/jpeg;base64,${ data.source }`;
break;
case data.source instanceof Blob:
source.src = window.URL.createObjectURL( data.source );
break;
case data.source instanceof ArrayBuffer:
const bytes = new Uint8Array( data.source );
let binaryData = "";
for (let i = 0, len = bytes.byteLength; i < len; i++)
{
binaryData += String.fromCharCode( bytes[ i ] );
}
source.src = `data:image/jpeg;base64,${ window.btoa( binaryData ) }`;
break;
}
} );
}
}
new FileStream( "anonymous.png" ).pipe( new ToImagePipe() ).then( ( event ) =>
{
const image = event.data;
}, ( event ) =>
{
const error = event.data;
throw error;
} );