UNPKG

2.67 kBJavaScriptView Raw
1"use strict";
2
3// this prevents Rekuire from being cached, so 'parent' is always updated
4delete require.cache[require.resolve(__filename)];
5
6var path = require('path'),
7 _ = require('underscore'),
8 isString = require('./helpers/isString'),
9 scan = require('./helpers/scan');
10var extensions = ['.js','.json','.coffee'];
11var baseDir = path.normalize( __dirname + "/../../../");
12var scanResults = scan(baseDir,extensions);
13var filesInProject = scanResults.filesInProject;
14var ambiguousFileNames = scanResults.ambiguousFileNames;
15
16module.exports = rekuire;
17
18function rekuire(requirement){
19 if (isString(requirement)){
20 return getModule(requirement).module
21 }else{
22 return {
23 path: getPath
24 }
25 }
26}
27
28rekuire.path = function(requirement){
29 return getPath(requirement);
30}
31
32rekuire.ignore = function(/*args*/){
33 var args = Array.prototype.slice.call(arguments);
34 scanResults = scan.setIgnoreAndRescan(args)
35 filesInProject = scanResults.filesInProject;
36 ambiguousFileNames = scanResults.ambiguousFileNames;
37}
38
39function getPath(requirement){
40 var location = getModule(requirement).path;
41 if (location === undefined){
42 throw "Could not locate a local for a module named ["+requirement+"]";
43 }
44 return location;
45}
46
47
48function getModule(requirement){
49 var calleePath = path.dirname(module.parent.filename);
50 var parentReq = module.parent.require.bind(module);
51 var retModule = null;
52 var modulePath = null;
53 var error = "";
54
55 if (ambiguousFileNames[requirement] !== undefined){
56 throw new Error('Ambiguity Error: There are more then one files that is named '+requirement);
57 }
58
59 if ( filesInProject[requirement] !== undefined){
60 // User typed in a relative path
61 retModule = parentReq(filesInProject[requirement]);
62 modulePath = filesInProject[requirement];
63 }else{
64 // User typed in a module name
65 modulePath = path.normalize(calleePath+"/"+requirement);
66 try{
67 retModule = parentReq(modulePath);
68 }catch(e){
69 // module by that name was not found in the scan, maybe it's a general node module.
70 error += e +"\n";
71 }
72
73 // General node module
74 if (retModule == null){
75 modulePath = requirement;
76 try{
77 retModule = parentReq(requirement);
78 }catch(e){
79 error += e +"\n";
80 }
81 }
82 }
83 if(!retModule){
84 throw new Error("Can not find a module by the name of ["+requirement+"] or it has returned empty. nested: "+error);
85 }
86 return { module: retModule, path: modulePath};
87}