import { Tube } from '../component' ; import StreamFactory from '../helpers/stream-factory' ; import { createWriteStream } from 'fs' ; import { join } from 'path' ; /**
 * Component that writes passing incoming/outgoing streams
 * interleaved to a filestream. The resulting stream (file) stores
 * messages as a JSON array, where each element has a type, timestamp,
 * and the original message (that went through the stream).
 */ export class Recorder extends Tube { param fileStream constructor ( fileStream ) { const incoming = StreamFactory . recorder ( 'incoming' , fileStream ) ; const outgoing = StreamFactory . recorder ( 'outgoing' , fileStream ) ; const interleaved = { incoming , outgoing } ; const streamsFinished = [ ] ; for ( const [ key , value ] of Object . entries ( interleaved ) ) { streamsFinished . push ( new Promise < void > ( ( resolve ) => value . on ( 'finish' , ( ) => { const timestamp = Date . now ( ) ; const message = null ; const type = key ; fileStream . write ( JSON . stringify ( { type , timestamp , message } , null , 2 ) ) ; fileStream . write ( ',\n' ) ; resolve ( ) ; } ) ) ) ; } fileStream . write ( '[\n' ) ; Promise . all ( streamsFinished ) . then ( ( ) => { fileStream . write ( JSON . stringify ( null ) ) ; fileStream . write ( '\n]\n' ) ; } ) . catch ( ( ) => { } ) ; super ( incoming , outgoing ) ; } param filename static toFile ( filename = 'data.json' ) { const cwd = process . cwd ( ) ; const fileStream = createWriteStream ( join ( cwd , filename ) ) ; return new Recorder ( fileStream ) ; } }