import ServiceElectron , { IPCMessages } from '../service.electron' ; import { FileParsers , AFileParser } from '../../controllers/files.parsers/index' ; import Logger from '../../tools/env.logger' ; import * as fs from 'fs' ; import * as path from 'path' ; import { Subscription } from '../../tools/index' ; import { IService } from '../../interfaces/interface.service' ; class description class ServiceFileReader implements IService { private _logger : Logger = new Logger ( 'ServiceFileReader' ) ; private _subscription : { [ key ] : Subscription ; } = { } ; returns public init ( ) { return new Promise ( ( resolve , reject ) => { ServiceElectron . IPC . subscribe ( IPCMessages . FileReadRequest , this . _onFileReadRequest . bind ( this ) ) . then ( ( subscription ) => { this . _subscription . FileReadRequest = subscription ; resolve ( ) ; } ) . catch ( ( error ) => { this . _logger . error ( `Fail to init module due error: ${ error . message }` ) ; reject ( error ) ; } ) ; } ) ; } public destroy ( ) { return new Promise ( ( resolve ) => { Object . keys ( this . _subscription ) . forEach ( ( key ) => { this . _subscription [ key ] . destroy ( ) ; } ) ; resolve ( ) ; } ) ; } public getName ( ) { return 'ServiceFileReader' ; } public getParser ( name ) { let parserClass ; FileParsers . forEach ( ( parser ) => { if ( parserClass !== undefined ) { return ; } if ( name === parser . name ) { parserClass = parser . class ; } } ) ; return parserClass ; } private _onFileReadRequest ( request , response ) { const req = request as IPCMessages . FileReadRequest ; fs . stat ( req . file , ( error , stats ) => { if ( error ) { return response ( new IPCMessages . FileReadResponse ( { size : 0 , error : error . message , content : '' , } ) ) ; } this . _read ( req . file , req . bytes > stats . size ? stats . size : req . bytes ) . then ( ( content ) => { response ( new IPCMessages . FileReadResponse ( { size : stats . size , content : content , } ) ) ; } ) . catch ( ( readingError ) => { response ( new IPCMessages . FileReadResponse ( { size : 0 , error : readingError . message , content : '' , } ) ) ; } ) ; } ) ; } private _read ( file , bytes ) { return new Promise ( ( resolve , reject ) => { const options = { autoClose : true , encoding : 'utf8' , start : 0 , end : bytes } ; let output = '' ; const stream = fs . createReadStream ( file , options ) ; stream . on ( 'data' , ( chunk ) => { output += chunk ; if ( stream !== undefined && stream . bytesRead >= ( options . end - options . start ) ) { stream . close ( ) ; stream . removeAllListeners ( ) ; resolve ( output ) ; } } ) ; stream . on ( 'end' , ( ) => { if ( stream !== undefined ) { stream . close ( ) ; stream . removeAllListeners ( ) ; } resolve ( output ) ; } ) ; } ) ; } } export default ( new ServiceFileReader ( ) ) ;