import { Transform , TransformCallback } from 'stream' ; import { detect } from './CSV' ; import { Parser } from './Parser' ; import { Quote , Comma } from './types' ; export class Streamer extends Transform { buffer : string ; sep ? : Comma ; quo ? : Quote ; constructor ( options ? ) { super ( { readableObjectMode : true , writableObjectMode : false , } ) ; this . buffer = '' ; this . sep = options && options . separator ; this . quo = options && options . quote ; } _transform ( chunk , _encoding , callback ) { this . buffer = this . buffer . concat ( chunk . toString ( ) ) ; if ( this . sep === undefined ) { this . sep = detect ( this . buffer ) ; } const csv = new Parser ( this . buffer , this . sep , this . quo ) ; const rows = csv . File ( ) ; if ( csv . linePointer !== csv . pointer ) { rows . pop ( ) ; } this . buffer = this . buffer . slice ( csv . linePointer ) ; if ( rows . length > 0 ) { rows . forEach ( ( row ) => { this . push ( row ) ; } ) ; } callback ( ) ; } _flush ( callback ) { const csv = new Parser ( this . buffer , this . sep , this . quo ) ; const rows = csv . File ( ) ; if ( rows . length > 0 ) { rows . forEach ( ( row ) => { this . push ( row ) ; } ) ; } callback ( ) ; } }