UNPKG

1.1 kBJavaScriptView Raw
1const fs = require('fs-extra')
2const path = require('path')
3
4const getCwd = require('../utils/get-cwd')
5
6/**
7 * 根据输入的字符串返回合法、存在的路径名
8 * @param {String} str
9 * @returns {String}
10 */
11module.exports = (str, cwd = '.') => {
12
13 if (isExist(str))
14 return str
15
16 {
17 const p = path.resolve(cwd, str)
18 if (isExist(p))
19 return p
20 }
21
22 {
23 const p = path.resolve(process.cwd(), str)
24 if (isExist(p))
25 return p
26 }
27
28 {
29 const p = path.resolve(getCwd(), str)
30 if (isExist(p))
31 return p
32 }
33
34 {
35 const p = path.resolve(getCwd(), 'node_modules', str)
36 if (isExist(p))
37 return p
38 }
39
40 return str
41}
42
43const isExist = (pathname) => {
44 if (fs.existsSync(pathname))
45 return true
46
47 if (fs.existsSync(pathname + '.js'))
48 return true
49
50 if (fs.existsSync(pathname + '.mjs'))
51 return true
52
53 if (fs.existsSync(pathname + '.jsx'))
54 return true
55
56 return false
57}