object.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. "use strict";
  2. var utf8 = require("./utf8");
  3. var utils = require("./utils");
  4. var GenericWorker = require("./stream/GenericWorker");
  5. var StreamHelper = require("./stream/StreamHelper");
  6. var defaults = require("./defaults");
  7. var CompressedObject = require("./compressedObject");
  8. var ZipObject = require("./zipObject");
  9. var generate = require("./generate");
  10. var nodejsUtils = require("./nodejsUtils");
  11. var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter");
  12. /**
  13. * Add a file in the current folder.
  14. * @private
  15. * @param {string} name the name of the file
  16. * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
  17. * @param {Object} originalOptions the options of the file
  18. * @return {Object} the new file.
  19. */
  20. var fileAdd = function(name, data, originalOptions) {
  21. // be sure sub folders exist
  22. var dataType = utils.getTypeOf(data),
  23. parent;
  24. /*
  25. * Correct options.
  26. */
  27. var o = utils.extend(originalOptions || {}, defaults);
  28. o.date = o.date || new Date();
  29. if (o.compression !== null) {
  30. o.compression = o.compression.toUpperCase();
  31. }
  32. if (typeof o.unixPermissions === "string") {
  33. o.unixPermissions = parseInt(o.unixPermissions, 8);
  34. }
  35. // UNX_IFDIR 0040000 see zipinfo.c
  36. if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
  37. o.dir = true;
  38. }
  39. // Bit 4 Directory
  40. if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
  41. o.dir = true;
  42. }
  43. if (o.dir) {
  44. name = forceTrailingSlash(name);
  45. }
  46. if (o.createFolders && (parent = parentFolder(name))) {
  47. folderAdd.call(this, parent, true);
  48. }
  49. var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false;
  50. if (!originalOptions || typeof originalOptions.binary === "undefined") {
  51. o.binary = !isUnicodeString;
  52. }
  53. var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;
  54. if (isCompressedEmpty || o.dir || !data || data.length === 0) {
  55. o.base64 = false;
  56. o.binary = true;
  57. data = "";
  58. o.compression = "STORE";
  59. dataType = "string";
  60. }
  61. /*
  62. * Convert content to fit.
  63. */
  64. var zipObjectContent = null;
  65. if (data instanceof CompressedObject || data instanceof GenericWorker) {
  66. zipObjectContent = data;
  67. } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {
  68. zipObjectContent = new NodejsStreamInputAdapter(name, data);
  69. } else {
  70. zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);
  71. }
  72. var object = new ZipObject(name, zipObjectContent, o);
  73. this.files[name] = object;
  74. /*
  75. TODO: we can't throw an exception because we have async promises
  76. (we can have a promise of a Date() for example) but returning a
  77. promise is useless because file(name, data) returns the JSZip
  78. object for chaining. Should we break that to allow the user
  79. to catch the error ?
  80. return external.Promise.resolve(zipObjectContent)
  81. .then(function () {
  82. return object;
  83. });
  84. */
  85. };
  86. /**
  87. * Find the parent folder of the path.
  88. * @private
  89. * @param {string} path the path to use
  90. * @return {string} the parent folder, or ""
  91. */
  92. var parentFolder = function (path) {
  93. if (path.slice(-1) === "/") {
  94. path = path.substring(0, path.length - 1);
  95. }
  96. var lastSlash = path.lastIndexOf("/");
  97. return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
  98. };
  99. /**
  100. * Returns the path with a slash at the end.
  101. * @private
  102. * @param {String} path the path to check.
  103. * @return {String} the path with a trailing slash.
  104. */
  105. var forceTrailingSlash = function(path) {
  106. // Check the name ends with a /
  107. if (path.slice(-1) !== "/") {
  108. path += "/"; // IE doesn't like substr(-1)
  109. }
  110. return path;
  111. };
  112. /**
  113. * Add a (sub) folder in the current folder.
  114. * @private
  115. * @param {string} name the folder's name
  116. * @param {boolean=} [createFolders] If true, automatically create sub
  117. * folders. Defaults to false.
  118. * @return {Object} the new folder.
  119. */
  120. var folderAdd = function(name, createFolders) {
  121. createFolders = (typeof createFolders !== "undefined") ? createFolders : defaults.createFolders;
  122. name = forceTrailingSlash(name);
  123. // Does this folder already exist?
  124. if (!this.files[name]) {
  125. fileAdd.call(this, name, null, {
  126. dir: true,
  127. createFolders: createFolders
  128. });
  129. }
  130. return this.files[name];
  131. };
  132. /**
  133. * Cross-window, cross-Node-context regular expression detection
  134. * @param {Object} object Anything
  135. * @return {Boolean} true if the object is a regular expression,
  136. * false otherwise
  137. */
  138. function isRegExp(object) {
  139. return Object.prototype.toString.call(object) === "[object RegExp]";
  140. }
  141. // return the actual prototype of JSZip
  142. var out = {
  143. /**
  144. * @see loadAsync
  145. */
  146. load: function() {
  147. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  148. },
  149. /**
  150. * Call a callback function for each entry at this folder level.
  151. * @param {Function} cb the callback function:
  152. * function (relativePath, file) {...}
  153. * It takes 2 arguments : the relative path and the file.
  154. */
  155. forEach: function(cb) {
  156. var filename, relativePath, file;
  157. // ignore warning about unwanted properties because this.files is a null prototype object
  158. /* eslint-disable-next-line guard-for-in */
  159. for (filename in this.files) {
  160. file = this.files[filename];
  161. relativePath = filename.slice(this.root.length, filename.length);
  162. if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root
  163. cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...
  164. }
  165. }
  166. },
  167. /**
  168. * Filter nested files/folders with the specified function.
  169. * @param {Function} search the predicate to use :
  170. * function (relativePath, file) {...}
  171. * It takes 2 arguments : the relative path and the file.
  172. * @return {Array} An array of matching elements.
  173. */
  174. filter: function(search) {
  175. var result = [];
  176. this.forEach(function (relativePath, entry) {
  177. if (search(relativePath, entry)) { // the file matches the function
  178. result.push(entry);
  179. }
  180. });
  181. return result;
  182. },
  183. /**
  184. * Add a file to the zip file, or search a file.
  185. * @param {string|RegExp} name The name of the file to add (if data is defined),
  186. * the name of the file to find (if no data) or a regex to match files.
  187. * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
  188. * @param {Object} o File options
  189. * @return {JSZip|Object|Array} this JSZip object (when adding a file),
  190. * a file (when searching by string) or an array of files (when searching by regex).
  191. */
  192. file: function(name, data, o) {
  193. if (arguments.length === 1) {
  194. if (isRegExp(name)) {
  195. var regexp = name;
  196. return this.filter(function(relativePath, file) {
  197. return !file.dir && regexp.test(relativePath);
  198. });
  199. }
  200. else { // text
  201. var obj = this.files[this.root + name];
  202. if (obj && !obj.dir) {
  203. return obj;
  204. } else {
  205. return null;
  206. }
  207. }
  208. }
  209. else { // more than one argument : we have data !
  210. name = this.root + name;
  211. fileAdd.call(this, name, data, o);
  212. }
  213. return this;
  214. },
  215. /**
  216. * Add a directory to the zip file, or search.
  217. * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
  218. * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
  219. */
  220. folder: function(arg) {
  221. if (!arg) {
  222. return this;
  223. }
  224. if (isRegExp(arg)) {
  225. return this.filter(function(relativePath, file) {
  226. return file.dir && arg.test(relativePath);
  227. });
  228. }
  229. // else, name is a new folder
  230. var name = this.root + arg;
  231. var newFolder = folderAdd.call(this, name);
  232. // Allow chaining by returning a new object with this folder as the root
  233. var ret = this.clone();
  234. ret.root = newFolder.name;
  235. return ret;
  236. },
  237. /**
  238. * Delete a file, or a directory and all sub-files, from the zip
  239. * @param {string} name the name of the file to delete
  240. * @return {JSZip} this JSZip object
  241. */
  242. remove: function(name) {
  243. name = this.root + name;
  244. var file = this.files[name];
  245. if (!file) {
  246. // Look for any folders
  247. if (name.slice(-1) !== "/") {
  248. name += "/";
  249. }
  250. file = this.files[name];
  251. }
  252. if (file && !file.dir) {
  253. // file
  254. delete this.files[name];
  255. } else {
  256. // maybe a folder, delete recursively
  257. var kids = this.filter(function(relativePath, file) {
  258. return file.name.slice(0, name.length) === name;
  259. });
  260. for (var i = 0; i < kids.length; i++) {
  261. delete this.files[kids[i].name];
  262. }
  263. }
  264. return this;
  265. },
  266. /**
  267. * @deprecated This method has been removed in JSZip 3.0, please check the upgrade guide.
  268. */
  269. generate: function() {
  270. throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.");
  271. },
  272. /**
  273. * Generate the complete zip file as an internal stream.
  274. * @param {Object} options the options to generate the zip file :
  275. * - compression, "STORE" by default.
  276. * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
  277. * @return {StreamHelper} the streamed zip file.
  278. */
  279. generateInternalStream: function(options) {
  280. var worker, opts = {};
  281. try {
  282. opts = utils.extend(options || {}, {
  283. streamFiles: false,
  284. compression: "STORE",
  285. compressionOptions : null,
  286. type: "",
  287. platform: "DOS",
  288. comment: null,
  289. mimeType: "application/zip",
  290. encodeFileName: utf8.utf8encode
  291. });
  292. opts.type = opts.type.toLowerCase();
  293. opts.compression = opts.compression.toUpperCase();
  294. // "binarystring" is preferred but the internals use "string".
  295. if(opts.type === "binarystring") {
  296. opts.type = "string";
  297. }
  298. if (!opts.type) {
  299. throw new Error("No output type specified.");
  300. }
  301. utils.checkSupport(opts.type);
  302. // accept nodejs `process.platform`
  303. if(
  304. opts.platform === "darwin" ||
  305. opts.platform === "freebsd" ||
  306. opts.platform === "linux" ||
  307. opts.platform === "sunos"
  308. ) {
  309. opts.platform = "UNIX";
  310. }
  311. if (opts.platform === "win32") {
  312. opts.platform = "DOS";
  313. }
  314. var comment = opts.comment || this.comment || "";
  315. worker = generate.generateWorker(this, opts, comment);
  316. } catch (e) {
  317. worker = new GenericWorker("error");
  318. worker.error(e);
  319. }
  320. return new StreamHelper(worker, opts.type || "string", opts.mimeType);
  321. },
  322. /**
  323. * Generate the complete zip file asynchronously.
  324. * @see generateInternalStream
  325. */
  326. generateAsync: function(options, onUpdate) {
  327. return this.generateInternalStream(options).accumulate(onUpdate);
  328. },
  329. /**
  330. * Generate the complete zip file asynchronously.
  331. * @see generateInternalStream
  332. */
  333. generateNodeStream: function(options, onUpdate) {
  334. options = options || {};
  335. if (!options.type) {
  336. options.type = "nodebuffer";
  337. }
  338. return this.generateInternalStream(options).toNodejsStream(onUpdate);
  339. }
  340. };
  341. module.exports = out;