설명 없음

RNFetchBlobReadStream.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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, 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. if(this._onError)
  42. this._onError(detail)
  43. else
  44. throw new Error(detail)
  45. }
  46. // when stream closed or error, remove event handler
  47. if (event === 'error' || event === 'end') {
  48. subscription.remove()
  49. this.closed = true
  50. }
  51. })
  52. }
  53. open() {
  54. if(!this.closed)
  55. RNFetchBlob.readStream(this.path, this.encoding, this.bufferSize || 10240 , this.tick || -1, this.streamId)
  56. else
  57. throw new Error('Stream closed')
  58. }
  59. onData(fn:() => void) {
  60. this._onData = fn
  61. }
  62. onError(fn) {
  63. this._onError = fn
  64. }
  65. onEnd (fn) {
  66. this._onEnd = fn
  67. }
  68. }