Keine Beschreibung

RNFetchBlobReadStream.js 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2016 wkh237@github. All rights reserved.
  2. // Use of this source code is governed by a MIT-style license that can be
  3. // found in the LICENSE file.
  4. import {
  5. NativeModules,
  6. DeviceEventEmitter,
  7. NativeAppEventEmitter,
  8. } from 'react-native'
  9. import UUID from '../utils/uuid'
  10. const RNFetchBlob = NativeModules.RNFetchBlob
  11. const emitter = DeviceEventEmitter
  12. export default class RNFetchBlobReadStream {
  13. path : string;
  14. encoding : 'utf8' | 'ascii' | 'base64';
  15. bufferSize : ?number;
  16. closed : boolean;
  17. tick : number = 10;
  18. constructor(path:string, encoding:string, bufferSize?:?number, tick:number) {
  19. if(!path)
  20. throw Error('RNFetchBlob could not open file stream with empty `path`')
  21. this.encoding = encoding || 'utf8'
  22. this.bufferSize = bufferSize
  23. this.path = path
  24. this.closed = false
  25. this.tick = tick
  26. this._onData = () => {}
  27. this._onEnd = () => {}
  28. this._onError = () => {}
  29. this.streamId = 'RNFBRS'+ UUID()
  30. // register for file stream event
  31. let subscription = emitter.addListener(this.streamId, (e) => {
  32. let {event, code, detail} = e
  33. if(this._onData && event === 'data') {
  34. this._onData(detail)
  35. return
  36. }
  37. else if (this._onEnd && event === 'end') {
  38. this._onEnd(detail)
  39. }
  40. else {
  41. const err = new Error(detail)
  42. err.code = code || 'EUNSPECIFIED'
  43. if(this._onError)
  44. this._onError(err)
  45. else
  46. throw err
  47. }
  48. // when stream closed or error, remove event handler
  49. if (event === 'error' || event === 'end') {
  50. subscription.remove()
  51. this.closed = true
  52. }
  53. })
  54. }
  55. open() {
  56. if(!this.closed)
  57. RNFetchBlob.readStream(this.path, this.encoding, this.bufferSize || 10240 , this.tick || -1, this.streamId)
  58. else
  59. throw new Error('Stream closed')
  60. }
  61. onData(fn:() => void) {
  62. this._onData = fn
  63. }
  64. onError(fn) {
  65. this._onError = fn
  66. }
  67. onEnd (fn) {
  68. this._onEnd = fn
  69. }
  70. }