1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | "use strict";
|
8 |
|
9 | var fs = require("fs");
|
10 | var Module = require("module");
|
11 | var path = require("path");
|
12 |
|
13 | var debug = require("debug")("akyuu:require");
|
14 |
|
15 | var _resolveFilename = Module._resolveFilename.bind(Module);
|
16 | var cache = {};
|
17 |
|
18 | var SRC_PATH = [];
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | Module._resolveFilename = function(request, parent) {
|
27 | if(!request.startsWith("./") && !request.startsWith("../")) {
|
28 | var _cache = cache[request];
|
29 |
|
30 | if(undefined !== _cache && typeof _cache !== Boolean && typeof _cache !== String) {
|
31 | cache[request] = _cache = undefined;
|
32 | }
|
33 |
|
34 | if(_cache) {
|
35 | request = cache[request];
|
36 | } else if(undefined === _cache) {
|
37 | _cache = cache[request] = false;
|
38 |
|
39 | for(var i = 0; i < SRC_PATH.length; i++) {
|
40 | var testRequest = path.resolve(SRC_PATH[i], request);
|
41 | var names = [
|
42 | testRequest + ".js",
|
43 | testRequest + ".json",
|
44 | testRequest + ".node",
|
45 | testRequest + "/index.js",
|
46 | testRequest + "/index.json",
|
47 | testRequest + "/index.node"
|
48 | ];
|
49 |
|
50 | for(var j = 0; j < names.length; j++) {
|
51 | try {
|
52 | |
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 | if(fs.statSync(names[j]).isFile()) {
|
62 | request = _cache = cache[request] = testRequest;
|
63 | break;
|
64 | }
|
65 | } catch(e) {
|
66 |
|
67 | }
|
68 | }
|
69 |
|
70 | if(_cache) break;
|
71 | }
|
72 | }
|
73 | }
|
74 |
|
75 | return _resolveFilename(request, parent);
|
76 | };
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 | exports.addRequirePath = function(path) {
|
83 | if(SRC_PATH.indexOf(path) >= 0) return;
|
84 | SRC_PATH.push(path);
|
85 |
|
86 | debug("add path " + path, SRC_PATH);
|
87 | };
|
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 | exports.removeRequirePath = function(path) {
|
94 | exports.paths = SRC_PATH = SRC_PATH.filter(function(value) {
|
95 | if(path === value) {
|
96 | cache = {};
|
97 | return false;
|
98 | } else {
|
99 | return true;
|
100 | }
|
101 | });
|
102 |
|
103 | debug("remove path " + path, SRC_PATH);
|
104 | };
|
105 |
|
106 | exports.paths = SRC_PATH;
|