No Description

load.js 2.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. 'use strict';
  2. var utils = require('./utils');
  3. var external = require("./external");
  4. var utf8 = require('./utf8');
  5. var utils = require('./utils');
  6. var ZipEntries = require('./zipEntries');
  7. var Crc32Probe = require('./stream/Crc32Probe');
  8. var nodejsUtils = require("./nodejsUtils");
  9. /**
  10. * Check the CRC32 of an entry.
  11. * @param {ZipEntry} zipEntry the zip entry to check.
  12. * @return {Promise} the result.
  13. */
  14. function checkEntryCRC32(zipEntry) {
  15. return new external.Promise(function (resolve, reject) {
  16. var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());
  17. worker.on("error", function (e) {
  18. reject(e);
  19. })
  20. .on("end", function () {
  21. if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {
  22. reject(new Error("Corrupted zip : CRC32 mismatch"));
  23. } else {
  24. resolve();
  25. }
  26. })
  27. .resume();
  28. });
  29. }
  30. module.exports = function(data, options) {
  31. var zip = this;
  32. options = utils.extend(options || {}, {
  33. base64: false,
  34. checkCRC32: false,
  35. optimizedBinaryString: false,
  36. createFolders: false,
  37. decodeFileName: utf8.utf8decode
  38. });
  39. if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  40. return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));
  41. }
  42. return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64)
  43. .then(function(data) {
  44. var zipEntries = new ZipEntries(options);
  45. zipEntries.load(data);
  46. return zipEntries;
  47. }).then(function checkCRC32(zipEntries) {
  48. var promises = [external.Promise.resolve(zipEntries)];
  49. var files = zipEntries.files;
  50. if (options.checkCRC32) {
  51. for (var i = 0; i < files.length; i++) {
  52. promises.push(checkEntryCRC32(files[i]));
  53. }
  54. }
  55. return external.Promise.all(promises);
  56. }).then(function addFiles(results) {
  57. var zipEntries = results.shift();
  58. var files = zipEntries.files;
  59. for (var i = 0; i < files.length; i++) {
  60. var input = files[i];
  61. zip.file(input.fileNameStr, input.decompressed, {
  62. binary: true,
  63. optimizedBinaryString: true,
  64. date: input.date,
  65. dir: input.dir,
  66. comment : input.fileCommentStr.length ? input.fileCommentStr : null,
  67. unixPermissions : input.unixPermissions,
  68. dosPermissions : input.dosPermissions,
  69. createFolders: options.createFolders
  70. });
  71. }
  72. if (zipEntries.zipComment.length) {
  73. zip.comment = zipEntries.zipComment;
  74. }
  75. return zip;
  76. });
  77. };