zipfile.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. var base64js = require("base64-js");
  2. var JSZip = require("jszip");
  3. exports.openArrayBuffer = openArrayBuffer;
  4. exports.splitPath = splitPath;
  5. exports.joinPath = joinPath;
  6. function openArrayBuffer(arrayBuffer) {
  7. return JSZip.loadAsync(arrayBuffer).then(function(zipFile) {
  8. function exists(name) {
  9. return zipFile.file(name) !== null;
  10. }
  11. function read(name, encoding) {
  12. return zipFile.file(name).async("uint8array").then(function(array) {
  13. if (encoding === "base64") {
  14. return base64js.fromByteArray(array);
  15. } else if (encoding) {
  16. var decoder = new TextDecoder(encoding);
  17. return decoder.decode(array);
  18. } else {
  19. return array;
  20. }
  21. });
  22. }
  23. function write(name, contents) {
  24. zipFile.file(name, contents);
  25. }
  26. function toArrayBuffer() {
  27. return zipFile.generateAsync({type: "arraybuffer"});
  28. }
  29. return {
  30. exists: exists,
  31. read: read,
  32. write: write,
  33. toArrayBuffer: toArrayBuffer
  34. };
  35. });
  36. }
  37. function splitPath(path) {
  38. var lastIndex = path.lastIndexOf("/");
  39. if (lastIndex === -1) {
  40. return {dirname: "", basename: path};
  41. } else {
  42. return {
  43. dirname: path.substring(0, lastIndex),
  44. basename: path.substring(lastIndex + 1)
  45. };
  46. }
  47. }
  48. function joinPath() {
  49. var nonEmptyPaths = Array.prototype.filter.call(arguments, function(path) {
  50. return path;
  51. });
  52. var relevantPaths = [];
  53. nonEmptyPaths.forEach(function(path) {
  54. if (/^\//.test(path)) {
  55. relevantPaths = [path];
  56. } else {
  57. relevantPaths.push(path);
  58. }
  59. });
  60. return relevantPaths.join("/");
  61. }