fs.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /**
  2. * Extended version of the standard `fs` module.
  3. * @module jsdoc/fs
  4. */
  5. const fs = require('fs');
  6. const path = require('path');
  7. const mkdirp = require('mkdirp');
  8. const ls = exports.ls = (dir, recurse, _allFiles, _path) => {
  9. let file;
  10. let files;
  11. let isFile;
  12. // first pass
  13. if (_path === undefined) {
  14. _allFiles = [];
  15. _path = [dir];
  16. }
  17. if (!_path.length) {
  18. return _allFiles;
  19. }
  20. if (recurse === undefined) {
  21. recurse = 1;
  22. }
  23. try {
  24. isFile = fs.statSync(dir).isFile();
  25. }
  26. catch (e) {
  27. isFile = false;
  28. }
  29. if (isFile) {
  30. files = [dir];
  31. }
  32. else {
  33. files = fs.readdirSync(dir);
  34. }
  35. for (let i = 0, l = files.length; i < l; i++) {
  36. file = String(files[i]);
  37. // skip dot files
  38. if (file.match(/^\.[^./\\]/)) {
  39. continue;
  40. }
  41. if ( fs.statSync(path.join(_path.join('/'), file)).isDirectory() ) {
  42. // it's a directory
  43. _path.push(file);
  44. if (_path.length - 1 < recurse) {
  45. ls(_path.join('/'), recurse, _allFiles, _path);
  46. }
  47. _path.pop();
  48. }
  49. else {
  50. // it's a file
  51. _allFiles.push( path.normalize(path.join(_path.join('/'), file)) );
  52. }
  53. }
  54. return _allFiles;
  55. };
  56. exports.toDir = _path => {
  57. let isDirectory;
  58. _path = path.normalize(_path);
  59. try {
  60. isDirectory = fs.statSync(_path).isDirectory();
  61. }
  62. catch (e) {
  63. isDirectory = false;
  64. }
  65. if (isDirectory) {
  66. return _path;
  67. } else {
  68. return path.dirname(_path);
  69. }
  70. };
  71. exports.mkPath = _path => {
  72. if ( Array.isArray(_path) ) {
  73. _path = _path.join('');
  74. }
  75. mkdirp.sync(_path);
  76. };
  77. exports.copyFileSync = (inFile, outDir = '', fileName) => {
  78. fileName = fileName || path.basename(inFile);
  79. fs.copyFileSync(inFile, path.join(outDir, fileName));
  80. };
  81. const alwaysOverride = {
  82. 'copyFileSync': true
  83. };
  84. Object.keys(fs).forEach(member => {
  85. if (!alwaysOverride[member]) {
  86. exports[member] = fs[member];
  87. }
  88. });