klaw-sync.js 1021 B

1234567891011121314151617181920212223242526272829
  1. 'use strict'
  2. const fs = require('graceful-fs')
  3. const path = require('path')
  4. function klawSync (dir, opts, ls) {
  5. if (!ls) {
  6. ls = []
  7. dir = path.resolve(dir)
  8. opts = opts || {}
  9. opts.fs = opts.fs || fs
  10. if (opts.depthLimit > -1) opts.rootDepth = dir.split(path.sep).length + 1
  11. }
  12. const paths = opts.fs.readdirSync(dir).map(p => dir + path.sep + p)
  13. for (var i = 0; i < paths.length; i += 1) {
  14. const pi = paths[i]
  15. const st = opts.fs.statSync(pi)
  16. const item = {path: pi, stats: st}
  17. const isUnderDepthLimit = (!opts.rootDepth || pi.split(path.sep).length - opts.rootDepth < opts.depthLimit)
  18. const filterResult = opts.filter ? opts.filter(item) : true
  19. const isDir = st.isDirectory()
  20. const shouldAdd = filterResult && (isDir ? !opts.nodir : !opts.nofile)
  21. const shouldTraverse = isDir && isUnderDepthLimit && (opts.traverseAll || filterResult)
  22. if (shouldAdd) ls.push(item)
  23. if (shouldTraverse) ls = klawSync(pi, opts, ls)
  24. }
  25. return ls
  26. }
  27. module.exports = klawSync