-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
46 lines (39 loc) · 1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const Module = require('module')
const fs = require('fs')
const path = require('path')
const CORE_MODULE_NAMES = Object.keys(process.binding('natives'))
function isCoreModule (name) {
return CORE_MODULE_NAMES.indexOf(name) > -1
}
module.exports = function (name, cwd) {
cwd = cwd || process.cwd()
// core modules
if (isCoreModule(name)) {
return name
}
// prepare a temp module file in cwd
let tempFilePrefix = path.join(cwd, './________for-getting-module-path')
let tempFile
while (true) {
tempFile = `${tempFilePrefix}.js`
try {
fs.statSync(tempFile)
tempFilePrefix += '_'
} catch (e) {
break
}
}
fs.writeFileSync(tempFile, 'module.exports = {}')
// load temp module
const tempModule = new Module(tempFile, null)
tempModule.load(tempFile)
// delete the temp module file
fs.unlinkSync(tempFile)
try {
// resolve module path
return Module._resolveFilename(name, tempModule)
} catch (e) {
console.error(e)
}
return ''
}