file.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. /*
  2. * Utilities: A classic collection of JavaScript utilities
  3. * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. let fs = require('fs');
  19. let path = require('path');
  20. /**
  21. @name file
  22. @namespace file
  23. */
  24. let fileUtils = new (function () {
  25. // Recursively copy files and directories
  26. let _copyFile = function (fromPath, toPath, opts) {
  27. let from = path.normalize(fromPath);
  28. let to = path.normalize(toPath);
  29. let options = opts || {};
  30. let fromStat;
  31. let toStat;
  32. let destExists;
  33. let destDoesNotExistErr;
  34. let content;
  35. let filename;
  36. let dirContents;
  37. let targetDir;
  38. fromStat = fs.statSync(from);
  39. try {
  40. //console.dir(to + ' destExists');
  41. toStat = fs.statSync(to);
  42. destExists = true;
  43. }
  44. catch(e) {
  45. //console.dir(to + ' does not exist');
  46. destDoesNotExistErr = e;
  47. destExists = false;
  48. }
  49. // Destination dir or file exists, copy into (directory)
  50. // or overwrite (file)
  51. if (destExists) {
  52. // If there's a rename-via-copy file/dir name passed, use it.
  53. // Otherwise use the actual file/dir name
  54. filename = options.rename || path.basename(from);
  55. // Copying a directory
  56. if (fromStat.isDirectory()) {
  57. dirContents = fs.readdirSync(from);
  58. targetDir = path.join(to, filename);
  59. // We don't care if the target dir already exists
  60. try {
  61. fs.mkdirSync(targetDir, {mode: fromStat.mode & 0o777});
  62. }
  63. catch(e) {
  64. if (e.code !== 'EEXIST') {
  65. throw e;
  66. }
  67. }
  68. for (let i = 0, ii = dirContents.length; i < ii; i++) {
  69. _copyFile(path.join(from, dirContents[i]), targetDir, {preserveMode: options.preserveMode});
  70. }
  71. }
  72. // Copying a file
  73. else {
  74. content = fs.readFileSync(from);
  75. let mode = fromStat.mode & 0o777;
  76. let targetFile = to;
  77. if (toStat.isDirectory()) {
  78. targetFile = path.join(to, filename);
  79. }
  80. let fileExists = fs.existsSync(targetFile);
  81. fs.writeFileSync(targetFile, content);
  82. // If the file didn't already exist, use the original file mode.
  83. // Otherwise, only update the mode if preserverMode is true.
  84. if(!fileExists || options.preserveMode) {
  85. fs.chmodSync(targetFile, mode);
  86. }
  87. }
  88. }
  89. // Dest doesn't exist, can't create it
  90. else {
  91. throw destDoesNotExistErr;
  92. }
  93. };
  94. // Remove the given directory
  95. let _rmDir = function (dirPath) {
  96. let dir = path.normalize(dirPath);
  97. let paths = [];
  98. paths = fs.readdirSync(dir);
  99. paths.forEach(function (p) {
  100. let curr = path.join(dir, p);
  101. let stat = fs.lstatSync(curr);
  102. if (stat.isDirectory()) {
  103. _rmDir(curr);
  104. }
  105. else {
  106. try {
  107. fs.unlinkSync(curr);
  108. } catch(e) {
  109. if (e.code === 'EPERM') {
  110. fs.chmodSync(curr, parseInt(666, 8));
  111. fs.unlinkSync(curr);
  112. } else {
  113. throw e;
  114. }
  115. }
  116. }
  117. });
  118. fs.rmdirSync(dir);
  119. };
  120. /**
  121. @name file#cpR
  122. @public
  123. @function
  124. @description Copies a directory/file to a destination
  125. @param {String} fromPath The source path to copy from
  126. @param {String} toPath The destination path to copy to
  127. @param {Object} opts Options to use
  128. @param {Boolean} [opts.preserveMode] If target file already exists, this
  129. determines whether the original file's mode is copied over. The default of
  130. false mimics the behavior of the `cp` command line tool. (Default: false)
  131. */
  132. this.cpR = function (fromPath, toPath, options) {
  133. let from = path.normalize(fromPath);
  134. let to = path.normalize(toPath);
  135. let toStat;
  136. let doesNotExistErr;
  137. let filename;
  138. let opts = options || {};
  139. if (from == to) {
  140. throw new Error('Cannot copy ' + from + ' to itself.');
  141. }
  142. // Handle rename-via-copy
  143. try {
  144. toStat = fs.statSync(to);
  145. }
  146. catch(e) {
  147. doesNotExistErr = e;
  148. // Get abs path so it's possible to check parent dir
  149. if (!this.isAbsolute(to)) {
  150. to = path.join(process.cwd(), to);
  151. }
  152. // Save the file/dir name
  153. filename = path.basename(to);
  154. // See if a parent dir exists, so there's a place to put the
  155. /// renamed file/dir (resets the destination for the copy)
  156. to = path.dirname(to);
  157. try {
  158. toStat = fs.statSync(to);
  159. }
  160. catch(e) {}
  161. if (toStat && toStat.isDirectory()) {
  162. // Set the rename opt to pass to the copy func, will be used
  163. // as the new file/dir name
  164. opts.rename = filename;
  165. //console.log('filename ' + filename);
  166. }
  167. else {
  168. throw doesNotExistErr;
  169. }
  170. }
  171. _copyFile(from, to, opts);
  172. };
  173. /**
  174. @name file#mkdirP
  175. @public
  176. @function
  177. @description Create the given directory(ies) using the given mode permissions
  178. @param {String} dir The directory to create
  179. @param {Number} mode The mode to give the created directory(ies)(Default: 0755)
  180. */
  181. this.mkdirP = function (dir, mode) {
  182. let dirPath = path.normalize(dir);
  183. let paths = dirPath.split(/\/|\\/);
  184. let currPath = '';
  185. let next;
  186. if (paths[0] == '' || /^[A-Za-z]+:/.test(paths[0])) {
  187. currPath = paths.shift() || '/';
  188. currPath = path.join(currPath, paths.shift());
  189. //console.log('basedir');
  190. }
  191. while ((next = paths.shift())) {
  192. if (next == '..') {
  193. currPath = path.join(currPath, next);
  194. continue;
  195. }
  196. currPath = path.join(currPath, next);
  197. try {
  198. //console.log('making ' + currPath);
  199. fs.mkdirSync(currPath, mode || parseInt(755, 8));
  200. }
  201. catch(e) {
  202. if (e.code != 'EEXIST') {
  203. throw e;
  204. }
  205. }
  206. }
  207. };
  208. /**
  209. @name file#rmRf
  210. @public
  211. @function
  212. @description Deletes the given directory/file
  213. @param {String} p The path to delete, can be a directory or file
  214. */
  215. this.rmRf = function (p, options) {
  216. let stat;
  217. try {
  218. stat = fs.lstatSync(p);
  219. if (stat.isDirectory()) {
  220. _rmDir(p);
  221. }
  222. else {
  223. fs.unlinkSync(p);
  224. }
  225. }
  226. catch (e) {}
  227. };
  228. /**
  229. @name file#isAbsolute
  230. @public
  231. @function
  232. @return {Boolean/String} If it's absolute the first character is returned otherwise false
  233. @description Checks if a given path is absolute or relative
  234. @param {String} p Path to check
  235. */
  236. this.isAbsolute = function (p) {
  237. let match = /^[A-Za-z]+:\\|^\//.exec(p);
  238. if (match && match.length) {
  239. return match[0];
  240. }
  241. return false;
  242. };
  243. /**
  244. @name file#absolutize
  245. @public
  246. @function
  247. @return {String} Returns the absolute path for the given path
  248. @description Returns the absolute path for the given path
  249. @param {String} p The path to get the absolute path for
  250. */
  251. this.absolutize = function (p) {
  252. if (this.isAbsolute(p)) {
  253. return p;
  254. }
  255. else {
  256. return path.join(process.cwd(), p);
  257. }
  258. };
  259. })();
  260. module.exports = fileUtils;