UNPKG

1.13 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 * @param {String} [cwd]
10 * @returns {String}
11 */
12module.exports = (str, cwd = '.') => {
13
14 if (isExist(str))
15 return str
16
17 {
18 const p = path.resolve(cwd, str)
19 if (isExist(p))
20 return p
21 }
22
23 {
24 const p = path.resolve(process.cwd(), str)
25 if (isExist(p))
26 return p
27 }
28
29 {
30 const p = path.resolve(getCwd(), str)
31 if (isExist(p))
32 return p
33 }
34
35 {
36 const p = path.resolve(getCwd(), 'node_modules', str)
37 if (isExist(p))
38 return p
39 }
40
41 return str
42}
43
44const isExist = (pathname) => {
45 if (fs.existsSync(pathname))
46 return true
47
48 if (fs.existsSync(pathname + '.js'))
49 return true
50
51 if (fs.existsSync(pathname + '.mjs'))
52 return true
53
54 if (fs.existsSync(pathname + '.jsx'))
55 return true
56
57 return false
58}