klaw-sync.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict'
  2. var path = require('path')
  3. var mm = require('micromatch')
  4. var fs
  5. try {
  6. fs = require('graceful-fs')
  7. } catch (e) {
  8. fs = require('fs')
  9. }
  10. function _procPath (dir, pathItem, opts, list) {
  11. var nestedPath
  12. var stat
  13. // here since dir already resolved, we use string concatenation
  14. // which showed faster performance than path.join() and path.resolve()
  15. if (path.sep === '/') {
  16. nestedPath = dir + '/' + pathItem
  17. } else {
  18. nestedPath = dir + '\\' + pathItem
  19. }
  20. stat = fs.lstatSync(nestedPath)
  21. if (stat.isDirectory()) {
  22. if (!opts.nodir) {
  23. list.push({path: nestedPath, stats: stat})
  24. }
  25. list = walkSync(nestedPath, opts, list)
  26. } else {
  27. if (!opts.nofile) {
  28. list.push({path: nestedPath, stats: stat})
  29. }
  30. }
  31. }
  32. function walkSync (dir, opts, list) {
  33. var files
  34. var ignore = []
  35. opts = opts || {}
  36. list = list || []
  37. dir = path.resolve(dir)
  38. try {
  39. files = fs.readdirSync(dir)
  40. if (opts.ignore) {
  41. ignore = mm(files, opts.ignore)
  42. }
  43. } catch (er) {
  44. throw er
  45. }
  46. for (var i = 0; i < files.length; i += 1) {
  47. var file = files[i]
  48. if (ignore.length > 0) {
  49. if (ignore.indexOf(file) === -1) _procPath(dir, file, opts, list)
  50. } else {
  51. _procPath(dir, file, opts, list)
  52. }
  53. }
  54. return list
  55. }
  56. module.exports = walkSync