UNPKG

3.06 kBJavaScriptView Raw
1/**
2 * XadillaX created at 2016-03-23 14:57:14 With ♥
3 *
4 * Copyright (c) 2016 akyuu.moe, all rights
5 * reserved.
6 */
7"use strict";
8
9var fs = require("fs");
10var Module = require("module");
11var path = require("path");
12
13var debug = require("debug")("akyuu:require");
14
15var _resolveFilename = Module._resolveFilename.bind(Module);
16var cache = {};
17
18var SRC_PATH = [];
19
20/**
21 * _resolveFilename
22 * @param {String} request the request path
23 * @param {Object} parent the parent object
24 * @return {*} the value which true `_resolveFilename` returned
25 */
26Module._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 * because:
54 *
55 * > Stability: 0 - Deprecated: Use fs.statSync or fs.accessSync instead.
56 *
57 * so we use `try ... catch` and `statSync` instead
58 *
59 * see see https://nodejs.org/api/fs.html#fs_fs_existssync_path
60 */
61 if(fs.statSync(names[j]).isFile()) {
62 request = _cache = cache[request] = testRequest;
63 break;
64 }
65 } catch(e) {
66 // ignore...
67 }
68 }
69
70 if(_cache) break;
71 }
72 }
73 }
74
75 return _resolveFilename(request, parent);
76};
77
78/**
79 * addRequirePath
80 * @param {String} path add a specified path to require path
81 */
82exports.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 * removeRequirePath
91 * @param {String} path remove a specified path from require path
92 */
93exports.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
106exports.paths = SRC_PATH;