index.js 659 B

12345678910111213141516171819202122232425262728293031
  1. var path = require('path')
  2. var fs = require('fs')
  3. function defaultCheck (dir) {
  4. return fs.existsSync(path.join(dir, 'package.json'))
  5. }
  6. function findRoot (start, check) {
  7. start = start || module.parent.filename
  8. check = check || defaultCheck
  9. if (typeof start === 'string') {
  10. if (start[start.length - 1] !== path.sep) {
  11. start += path.sep
  12. }
  13. start = start.split(path.sep)
  14. }
  15. if (!start.length) {
  16. throw new Error('package.json not found in path')
  17. }
  18. start.pop()
  19. var dir = start.join(path.sep)
  20. try {
  21. if (check(dir)) {
  22. return dir
  23. }
  24. } catch (e) {}
  25. return findRoot(start, check)
  26. }
  27. module.exports = findRoot