utils.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. const fsystem = require("./fileSystem").require();
  2. const pth = require("path");
  3. const Constants = require("./constants");
  4. const Errors = require("./errors");
  5. const isWin = typeof process === "object" && "win32" === process.platform;
  6. const is_Obj = (obj) => obj && typeof obj === "object";
  7. // generate CRC32 lookup table
  8. const crcTable = new Uint32Array(256).map((t, c) => {
  9. for (let k = 0; k < 8; k++) {
  10. if ((c & 1) !== 0) {
  11. c = 0xedb88320 ^ (c >>> 1);
  12. } else {
  13. c >>>= 1;
  14. }
  15. }
  16. return c >>> 0;
  17. });
  18. // UTILS functions
  19. function Utils(opts) {
  20. this.sep = pth.sep;
  21. this.fs = fsystem;
  22. if (is_Obj(opts)) {
  23. // custom filesystem
  24. if (is_Obj(opts.fs) && typeof opts.fs.statSync === "function") {
  25. this.fs = opts.fs;
  26. }
  27. }
  28. }
  29. module.exports = Utils;
  30. // INSTANCED functions
  31. Utils.prototype.makeDir = function (/*String*/ folder) {
  32. const self = this;
  33. // Sync - make directories tree
  34. function mkdirSync(/*String*/ fpath) {
  35. let resolvedPath = fpath.split(self.sep)[0];
  36. fpath.split(self.sep).forEach(function (name) {
  37. if (!name || name.substr(-1, 1) === ":") return;
  38. resolvedPath += self.sep + name;
  39. var stat;
  40. try {
  41. stat = self.fs.statSync(resolvedPath);
  42. } catch (e) {
  43. self.fs.mkdirSync(resolvedPath);
  44. }
  45. if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY.replace("%s", resolvedPath);
  46. });
  47. }
  48. mkdirSync(folder);
  49. };
  50. Utils.prototype.writeFileTo = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr) {
  51. const self = this;
  52. if (self.fs.existsSync(path)) {
  53. if (!overwrite) return false; // cannot overwrite
  54. var stat = self.fs.statSync(path);
  55. if (stat.isDirectory()) {
  56. return false;
  57. }
  58. }
  59. var folder = pth.dirname(path);
  60. if (!self.fs.existsSync(folder)) {
  61. self.makeDir(folder);
  62. }
  63. var fd;
  64. try {
  65. fd = self.fs.openSync(path, "w", 438); // 0666
  66. } catch (e) {
  67. self.fs.chmodSync(path, 438);
  68. fd = self.fs.openSync(path, "w", 438);
  69. }
  70. if (fd) {
  71. try {
  72. self.fs.writeSync(fd, content, 0, content.length, 0);
  73. } finally {
  74. self.fs.closeSync(fd);
  75. }
  76. }
  77. self.fs.chmodSync(path, attr || 438);
  78. return true;
  79. };
  80. Utils.prototype.writeFileToAsync = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr, /*Function*/ callback) {
  81. if (typeof attr === "function") {
  82. callback = attr;
  83. attr = undefined;
  84. }
  85. const self = this;
  86. self.fs.exists(path, function (exist) {
  87. if (exist && !overwrite) return callback(false);
  88. self.fs.stat(path, function (err, stat) {
  89. if (exist && stat.isDirectory()) {
  90. return callback(false);
  91. }
  92. var folder = pth.dirname(path);
  93. self.fs.exists(folder, function (exists) {
  94. if (!exists) self.makeDir(folder);
  95. self.fs.open(path, "w", 438, function (err, fd) {
  96. if (err) {
  97. self.fs.chmod(path, 438, function () {
  98. self.fs.open(path, "w", 438, function (err, fd) {
  99. self.fs.write(fd, content, 0, content.length, 0, function () {
  100. self.fs.close(fd, function () {
  101. self.fs.chmod(path, attr || 438, function () {
  102. callback(true);
  103. });
  104. });
  105. });
  106. });
  107. });
  108. } else if (fd) {
  109. self.fs.write(fd, content, 0, content.length, 0, function () {
  110. self.fs.close(fd, function () {
  111. self.fs.chmod(path, attr || 438, function () {
  112. callback(true);
  113. });
  114. });
  115. });
  116. } else {
  117. self.fs.chmod(path, attr || 438, function () {
  118. callback(true);
  119. });
  120. }
  121. });
  122. });
  123. });
  124. });
  125. };
  126. Utils.prototype.findFiles = function (/*String*/ path) {
  127. const self = this;
  128. function findSync(/*String*/ dir, /*RegExp*/ pattern, /*Boolean*/ recursive) {
  129. if (typeof pattern === "boolean") {
  130. recursive = pattern;
  131. pattern = undefined;
  132. }
  133. let files = [];
  134. self.fs.readdirSync(dir).forEach(function (file) {
  135. var path = pth.join(dir, file);
  136. if (self.fs.statSync(path).isDirectory() && recursive) files = files.concat(findSync(path, pattern, recursive));
  137. if (!pattern || pattern.test(path)) {
  138. files.push(pth.normalize(path) + (self.fs.statSync(path).isDirectory() ? self.sep : ""));
  139. }
  140. });
  141. return files;
  142. }
  143. return findSync(path, undefined, true);
  144. };
  145. Utils.prototype.getAttributes = function () {};
  146. Utils.prototype.setAttributes = function () {};
  147. // STATIC functions
  148. // crc32 single update (it is part of crc32)
  149. Utils.crc32update = function (crc, byte) {
  150. return crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);
  151. };
  152. Utils.crc32 = function (buf) {
  153. if (typeof buf === "string") {
  154. buf = Buffer.from(buf, "utf8");
  155. }
  156. // Generate crcTable
  157. if (!crcTable.length) genCRCTable();
  158. let len = buf.length;
  159. let crc = ~0;
  160. for (let off = 0; off < len; ) crc = Utils.crc32update(crc, buf[off++]);
  161. // xor and cast as uint32 number
  162. return ~crc >>> 0;
  163. };
  164. Utils.methodToString = function (/*Number*/ method) {
  165. switch (method) {
  166. case Constants.STORED:
  167. return "STORED (" + method + ")";
  168. case Constants.DEFLATED:
  169. return "DEFLATED (" + method + ")";
  170. default:
  171. return "UNSUPPORTED (" + method + ")";
  172. }
  173. };
  174. // removes ".." style path elements
  175. Utils.canonical = function (/*string*/ path) {
  176. if (!path) return "";
  177. // trick normalize think path is absolute
  178. var safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/"));
  179. return pth.join(".", safeSuffix);
  180. };
  181. // make abolute paths taking prefix as root folder
  182. Utils.sanitize = function (/*string*/ prefix, /*string*/ name) {
  183. prefix = pth.resolve(pth.normalize(prefix));
  184. var parts = name.split("/");
  185. for (var i = 0, l = parts.length; i < l; i++) {
  186. var path = pth.normalize(pth.join(prefix, parts.slice(i, l).join(pth.sep)));
  187. if (path.indexOf(prefix) === 0) {
  188. return path;
  189. }
  190. }
  191. return pth.normalize(pth.join(prefix, pth.basename(name)));
  192. };
  193. // converts buffer, Uint8Array, string types to buffer
  194. Utils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input) {
  195. if (Buffer.isBuffer(input)) {
  196. return input;
  197. } else if (input instanceof Uint8Array) {
  198. return Buffer.from(input);
  199. } else {
  200. // expect string all other values are invalid and return empty buffer
  201. return typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.alloc(0);
  202. }
  203. };
  204. Utils.readBigUInt64LE = function (/*Buffer*/ buffer, /*int*/ index) {
  205. var slice = Buffer.from(buffer.slice(index, index + 8));
  206. slice.swap64();
  207. return parseInt(`0x${slice.toString("hex")}`);
  208. };
  209. Utils.isWin = isWin; // Do we have windows system
  210. Utils.crcTable = crcTable;