説明なし

StreamHelper.js 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. 'use strict';
  2. var utils = require('../utils');
  3. var ConvertWorker = require('./ConvertWorker');
  4. var GenericWorker = require('./GenericWorker');
  5. var base64 = require('../base64');
  6. var support = require("../support");
  7. var external = require("../external");
  8. var NodejsStreamOutputAdapter = null;
  9. if (support.nodestream) {
  10. try {
  11. NodejsStreamOutputAdapter = require('../nodejs/NodejsStreamOutputAdapter');
  12. } catch(e) {}
  13. }
  14. /**
  15. * Apply the final transformation of the data. If the user wants a Blob for
  16. * example, it's easier to work with an U8intArray and finally do the
  17. * ArrayBuffer/Blob conversion.
  18. * @param {String} type the name of the final type
  19. * @param {String|Uint8Array|Buffer} content the content to transform
  20. * @param {String} mimeType the mime type of the content, if applicable.
  21. * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.
  22. */
  23. function transformZipOutput(type, content, mimeType) {
  24. switch(type) {
  25. case "blob" :
  26. return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType);
  27. case "base64" :
  28. return base64.encode(content);
  29. default :
  30. return utils.transformTo(type, content);
  31. }
  32. }
  33. /**
  34. * Concatenate an array of data of the given type.
  35. * @param {String} type the type of the data in the given array.
  36. * @param {Array} dataArray the array containing the data chunks to concatenate
  37. * @return {String|Uint8Array|Buffer} the concatenated data
  38. * @throws Error if the asked type is unsupported
  39. */
  40. function concat (type, dataArray) {
  41. var i, index = 0, res = null, totalLength = 0;
  42. for(i = 0; i < dataArray.length; i++) {
  43. totalLength += dataArray[i].length;
  44. }
  45. switch(type) {
  46. case "string":
  47. return dataArray.join("");
  48. case "array":
  49. return Array.prototype.concat.apply([], dataArray);
  50. case "uint8array":
  51. res = new Uint8Array(totalLength);
  52. for(i = 0; i < dataArray.length; i++) {
  53. res.set(dataArray[i], index);
  54. index += dataArray[i].length;
  55. }
  56. return res;
  57. case "nodebuffer":
  58. return Buffer.concat(dataArray);
  59. default:
  60. throw new Error("concat : unsupported type '" + type + "'");
  61. }
  62. }
  63. /**
  64. * Listen a StreamHelper, accumulate its content and concatenate it into a
  65. * complete block.
  66. * @param {StreamHelper} helper the helper to use.
  67. * @param {Function} updateCallback a callback called on each update. Called
  68. * with one arg :
  69. * - the metadata linked to the update received.
  70. * @return Promise the promise for the accumulation.
  71. */
  72. function accumulate(helper, updateCallback) {
  73. return new external.Promise(function (resolve, reject){
  74. var dataArray = [];
  75. var chunkType = helper._internalType,
  76. resultType = helper._outputType,
  77. mimeType = helper._mimeType;
  78. helper
  79. .on('data', function (data, meta) {
  80. dataArray.push(data);
  81. if(updateCallback) {
  82. updateCallback(meta);
  83. }
  84. })
  85. .on('error', function(err) {
  86. dataArray = [];
  87. reject(err);
  88. })
  89. .on('end', function (){
  90. try {
  91. var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType);
  92. resolve(result);
  93. } catch (e) {
  94. reject(e);
  95. }
  96. dataArray = [];
  97. })
  98. .resume();
  99. });
  100. }
  101. /**
  102. * An helper to easily use workers outside of JSZip.
  103. * @constructor
  104. * @param {Worker} worker the worker to wrap
  105. * @param {String} outputType the type of data expected by the use
  106. * @param {String} mimeType the mime type of the content, if applicable.
  107. */
  108. function StreamHelper(worker, outputType, mimeType) {
  109. var internalType = outputType;
  110. switch(outputType) {
  111. case "blob":
  112. case "arraybuffer":
  113. internalType = "uint8array";
  114. break;
  115. case "base64":
  116. internalType = "string";
  117. break;
  118. }
  119. try {
  120. // the type used internally
  121. this._internalType = internalType;
  122. // the type used to output results
  123. this._outputType = outputType;
  124. // the mime type
  125. this._mimeType = mimeType;
  126. utils.checkSupport(internalType);
  127. this._worker = worker.pipe(new ConvertWorker(internalType));
  128. // the last workers can be rewired without issues but we need to
  129. // prevent any updates on previous workers.
  130. worker.lock();
  131. } catch(e) {
  132. this._worker = new GenericWorker("error");
  133. this._worker.error(e);
  134. }
  135. }
  136. StreamHelper.prototype = {
  137. /**
  138. * Listen a StreamHelper, accumulate its content and concatenate it into a
  139. * complete block.
  140. * @param {Function} updateCb the update callback.
  141. * @return Promise the promise for the accumulation.
  142. */
  143. accumulate : function (updateCb) {
  144. return accumulate(this, updateCb);
  145. },
  146. /**
  147. * Add a listener on an event triggered on a stream.
  148. * @param {String} evt the name of the event
  149. * @param {Function} fn the listener
  150. * @return {StreamHelper} the current helper.
  151. */
  152. on : function (evt, fn) {
  153. var self = this;
  154. if(evt === "data") {
  155. this._worker.on(evt, function (chunk) {
  156. fn.call(self, chunk.data, chunk.meta);
  157. });
  158. } else {
  159. this._worker.on(evt, function () {
  160. utils.delay(fn, arguments, self);
  161. });
  162. }
  163. return this;
  164. },
  165. /**
  166. * Resume the flow of chunks.
  167. * @return {StreamHelper} the current helper.
  168. */
  169. resume : function () {
  170. utils.delay(this._worker.resume, [], this._worker);
  171. return this;
  172. },
  173. /**
  174. * Pause the flow of chunks.
  175. * @return {StreamHelper} the current helper.
  176. */
  177. pause : function () {
  178. this._worker.pause();
  179. return this;
  180. },
  181. /**
  182. * Return a nodejs stream for this helper.
  183. * @param {Function} updateCb the update callback.
  184. * @return {NodejsStreamOutputAdapter} the nodejs stream.
  185. */
  186. toNodejsStream : function (updateCb) {
  187. utils.checkSupport("nodestream");
  188. if (this._outputType !== "nodebuffer") {
  189. // an object stream containing blob/arraybuffer/uint8array/string
  190. // is strange and I don't know if it would be useful.
  191. // I you find this comment and have a good usecase, please open a
  192. // bug report !
  193. throw new Error(this._outputType + " is not supported by this method");
  194. }
  195. return new NodejsStreamOutputAdapter(this, {
  196. objectMode : this._outputType !== "nodebuffer"
  197. }, updateCb);
  198. }
  199. };
  200. module.exports = StreamHelper;