sync.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. var core = require('./core');
  2. var fs = require('fs');
  3. var path = require('path');
  4. var caller = require('./caller.js');
  5. var nodeModulesPaths = require('./node-modules-paths.js');
  6. module.exports = function (x, opts) {
  7. if (!opts) opts = {};
  8. var isFile = opts.isFile || function (file) {
  9. try { var stat = fs.statSync(file) }
  10. catch (err) { if (err && err.code === 'ENOENT') return false }
  11. return stat.isFile() || stat.isFIFO();
  12. };
  13. var readFileSync = opts.readFileSync || fs.readFileSync;
  14. var extensions = opts.extensions || [ '.js' ];
  15. var y = opts.basedir || path.dirname(caller());
  16. opts.paths = opts.paths || [];
  17. if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[\\\/])/.test(x)) {
  18. var res = path.resolve(y, x);
  19. if (x === '..') res += '/';
  20. var m = loadAsFileSync(res) || loadAsDirectorySync(res);
  21. if (m) return m;
  22. } else {
  23. var n = loadNodeModulesSync(x, y);
  24. if (n) return n;
  25. }
  26. if (core[x]) return x;
  27. throw new Error("Cannot find module '" + x + "' from '" + y + "'");
  28. function loadAsFileSync (x) {
  29. if (isFile(x)) {
  30. return x;
  31. }
  32. for (var i = 0; i < extensions.length; i++) {
  33. var file = x + extensions[i];
  34. if (isFile(file)) {
  35. return file;
  36. }
  37. }
  38. }
  39. function loadAsDirectorySync (x) {
  40. var pkgfile = path.join(x, '/package.json');
  41. if (isFile(pkgfile)) {
  42. var body = readFileSync(pkgfile, 'utf8');
  43. try {
  44. var pkg = JSON.parse(body);
  45. if (opts.packageFilter) {
  46. pkg = opts.packageFilter(pkg, x);
  47. }
  48. if (pkg.main) {
  49. var m = loadAsFileSync(path.resolve(x, pkg.main));
  50. if (m) return m;
  51. var n = loadAsDirectorySync(path.resolve(x, pkg.main));
  52. if (n) return n;
  53. }
  54. }
  55. catch (err) {}
  56. }
  57. return loadAsFileSync(path.join( x, '/index'));
  58. }
  59. function loadNodeModulesSync (x, start) {
  60. var dirs = nodeModulesPaths(start, opts);
  61. for (var i = 0; i < dirs.length; i++) {
  62. var dir = dirs[i];
  63. var m = loadAsFileSync(path.join( dir, '/', x));
  64. if (m) return m;
  65. var n = loadAsDirectorySync(path.join( dir, '/', x ));
  66. if (n) return n;
  67. }
  68. }
  69. };