node-modules-paths.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var path = require('path');
  2. var fs = require('fs');
  3. var parse = path.parse || require('path-parse');
  4. module.exports = function nodeModulesPaths(start, opts) {
  5. var modules = opts && opts.moduleDirectory
  6. ? [].concat(opts.moduleDirectory)
  7. : ['node_modules'];
  8. // ensure that `start` is an absolute path at this point,
  9. // resolving against the process' current working directory
  10. var absoluteStart = path.resolve(start);
  11. if (opts && opts.preserveSymlinks === false) {
  12. try {
  13. absoluteStart = fs.realpathSync(absoluteStart);
  14. } catch (err) {
  15. if (err.code !== 'ENOENT') {
  16. throw err;
  17. }
  18. }
  19. }
  20. var prefix = '/';
  21. if (/^([A-Za-z]:)/.test(absoluteStart)) {
  22. prefix = '';
  23. } else if (/^\\\\/.test(absoluteStart)) {
  24. prefix = '\\\\';
  25. }
  26. var paths = [absoluteStart];
  27. var parsed = parse(absoluteStart);
  28. while (parsed.dir !== paths[paths.length - 1]) {
  29. paths.push(parsed.dir);
  30. parsed = parse(parsed.dir);
  31. }
  32. var dirs = paths.reduce(function (dirs, aPath) {
  33. return dirs.concat(modules.map(function (moduleDir) {
  34. return path.join(prefix, aPath, moduleDir);
  35. }));
  36. }, []);
  37. return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
  38. };