import fs from 'fs' ; import path from 'path' ; function padNumber ( n ) { return n > 9 ? '' + n . toString ( ) : '0' + n . toString ( ) ; } class export class PacketLogger { private static clearDirectory ( dir ) { const files = fs . readdirSync ( dir ) ; for ( const file of files ) { fs . unlinkSync ( path . join ( dir , file ) ) ; } } private inPath : string ; private outPath : string ; constructor ( baseDir = 'packets' , incomingDir = 'in' , outgoingDir = 'out' ) { this . inPath = `${ baseDir }/${ incomingDir }/` ; this . outPath = `${ baseDir }/${ outgoingDir }/` ; console . log ( `PacketDumper: using ${ this . inPath } as incoming dir` ) ; console . log ( `PacketDumper: using ${ this . outPath } as outgoing dir` ) ; try { if ( fs . existsSync ( baseDir ) === false ) { fs . mkdirSync ( baseDir ) ; } if ( fs . existsSync ( this . inPath ) === true ) { console . log ( 'PacketDumper, cleaning in dir' ) ; PacketLogger . clearDirectory ( this . inPath ) ; } else { fs . mkdirSync ( this . inPath ) ; } if ( fs . existsSync ( this . outPath ) === true ) { console . log ( 'PacketDumper, cleaning out dir' ) ; PacketLogger . clearDirectory ( this . outPath ) ; } else { fs . mkdirSync ( this . outPath ) ; } } catch ( error ) { console . warn ( error ) ; } } param inPacket public dumpIn ( connUuid , seq , packetId , packetData ) { const packetPath = `${ this . inPath }${ connUuid }_${ padNumber ( seq ) }-${ packetId }.bin` ; fs . writeFileSync ( packetPath , packetData , { encoding : 'binary' , flag : 'w' } ) ; } param outPacket public dumpOut ( connUuid , seq , packetId , packetData ) { const packetPath = `${ this . outPath }${ connUuid }_${ padNumber ( seq ) }-${ packetId }.bin` ; fs . writeFileSync ( packetPath , packetData , { encoding : 'binary' , flag : 'w' } ) ; } }