streaming_fetch.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. ; (function (global) {
  2. /**
  3. * 流式资源加载
  4. * @param {string} url 资源链接
  5. * @param {object} callbacks 回调集合:{onBuffer,onDone,onError}
  6. */
  7. class StreamingFetcher {
  8. constructor(url, callbacks) {
  9. this.url = url;
  10. this._isDone = false;
  11. this._error = null;
  12. this._abortController = new AbortController();
  13. this._callbacks = callbacks ?? {};
  14. }
  15. /**
  16. * Test Only
  17. */
  18. testCallback() {
  19. console.log("Hello!");
  20. this._callbacks.onDone();
  21. this._callbacks.onBuffer(new Uint8Array([1, 2, 3]));
  22. this._callbacks.onError("1234545");
  23. }
  24. /**
  25. * 停止加载
  26. */
  27. stop() {
  28. var isRunning = this._isDone === false && this._error == null;
  29. if (isRunning) {
  30. this._abortController.abort();
  31. }
  32. }
  33. /**
  34. * 开始加载
  35. */
  36. start() {
  37. var that = this;
  38. fetch(this.url, {
  39. signal: this._abortController.signal,
  40. keepalive: true,
  41. headers: {
  42. 'Accept-Ranges': 'bytes',
  43. 'Range': 'bytes=0-',
  44. 'Connection': 'keep-alive'
  45. }
  46. }).then(response => {
  47. const reader = response.body.getReader();
  48. function read() {
  49. reader.read().then(({ done, value }) => {
  50. if (done) {
  51. var onDone = that._callbacks.onDone;
  52. onDone && onDone();
  53. return;
  54. }
  55. var onBuffer = that._callbacks.onBuffer;
  56. onBuffer && onBuffer(value);
  57. // 读取下一个数据
  58. read();
  59. })
  60. }
  61. read();
  62. }).catch((error) => {
  63. that._error = error;
  64. var onError = that._callbacks.onError;
  65. onError && onError(error.message);
  66. });
  67. }
  68. }
  69. global.StreamingFetcher = StreamingFetcher;
  70. })(window);