import * as fs from "fs-extra" ; import { IPipe , IPipeItems } from "../interfaces" ; export interface ICsvPipeOpts { name : string ; path : string ; items : IPipeItems ; } class CsvPipe { public name : string ; public items : IPipeItems ; private stream : fs . WriteStream ; private isFirst : boolean ; constructor ( opts ) { this . name = opts . name ; this . items = opts . items ; this . stream = fs . createWriteStream ( opts . path ) ; this . isFirst = true ; } param { Object } data public write ( data ) { let chunk = "" ; if ( this . isFirst ) { this . isFirst = false ; const headers = ( Array . isArray ( this . items ) ) ? this . items : Object . keys ( this . items ) ; chunk += headers . reduce ( ( str , c ) => `${ str },${ c }` ) + "\n" ; } chunk += data . reduce ( ( str , c ) => `${ str },${ c }` ) + "\n" ; this . stream . write ( chunk ) ; } public end ( ) { this . stream . end ( ) ; } } export default function csvPipe ( opts ) { return new CsvPipe ( opts ) ; }