UNPKG

1.1 kBJavaScriptView Raw
1'use strict'
2
3const debug = require('debug')('elint:env')
4const path = require('path')
5const isNpm = require('is-npm')
6
7/**
8 * 获取通过 npm script 执行时的项目根路径
9 *
10 * @returns {string} cwd
11 */
12/* istanbul ignore next */
13function getInitCwd () {
14 if (process.env.INIT_CWD) {
15 debug(`process.env.INIT_CWD: ${process.env.INIT_CWD}`)
16 return process.env.INIT_CWD
17 }
18
19 const cwd = process.cwd()
20
21 debug(`process.cwd(): ${cwd}`)
22
23 // 兼容 npm v3
24 return cwd.split(`${path.sep}node_modules${path.sep}`)[0]
25}
26
27/**
28 * 项目根目录
29 *
30 * @returns {string} base dir
31 */
32const getBaseDir = () => {
33 /* istanbul ignore next */
34 const baseDir = isNpm ? getInitCwd() : process.cwd()
35
36 debug(`isNpm: ${isNpm}`)
37 debug(`base dir: ${baseDir}`)
38
39 return baseDir
40}
41
42/**
43 * 项目的 node_modules 目录
44 *
45 * @returns {string} node_modules dir
46 */
47const getNodeModulesDir = () => {
48 const nodeModulesDir = path.join(getBaseDir(), 'node_modules')
49
50 debug(`node_modules dir: ${nodeModulesDir}`)
51 return nodeModulesDir
52}
53
54module.exports = {
55 getBaseDir,
56 getNodeModulesDir
57}