UNPKG

1.79 kBJavaScriptView Raw
1var findRoot = require('find-root');
2var caller = require('caller');
3
4/**
5 * @description Get caller root.
6 *
7 * Used by debug,
8 * because we want to find the root (where a package.json exists) nearest to the calling module.
9 * So that debug messages are output relative to the CALLER module
10 *
11 * caller dependency is able to detect the calling unit
12 * they are doing this with the trick of creating an error stack
13 * caller(2) means -> get me the previous calling unit
14 *
15 * Example Structure:
16 * Ghost
17 * node_modules
18 * ghost-ignition
19 * passport-ghost
20 *
21 * Ghost uses ghost-ignition and passport-ghost uses ghost-ignition.
22 *
23 * If passport-ghost calls ghost-ignition, caller(2) would return the last caller of this module
24 * If Ghost calls ghost-ignition, caller(2) would return the last caller of this module
25 * And findRoot will be able to get the latest path with a valid package.json
26 */
27exports.getCallerRoot = function getCallerRoot() {
28 try {
29 return findRoot(caller(2));
30 } catch (err) {
31 return;
32 }
33};
34
35/**
36 * @description Get current working directory.
37 *
38 * Used by config,
39 * because we want to find the root (where a package.json exists) nearest to the current working directory
40 * So that configuration uses the config file AT the CWD, or at the project root of the CWD
41 *
42 * process.cwd() is the path from which `node` was called
43 * usually, the root of a project, e.g. the same level as where package.json,
44 * config.*.json and node_modules folder would be found.
45 *
46 * However, in some cases, the CWD may be deeper in the project,
47 * e.g. if using a script, or using a childprocess.
48 */
49exports.getCWDRoot = function getCWDRoot() {
50 try {
51 return findRoot(process.cwd());
52 } catch (err) {
53 return;
54 }
55}