UNPKG

828 BPlain TextView Raw
1import * as dotenv from 'dotenv';
2import { fs, fsPath } from './libs';
3
4export interface IReadOptions {
5 path?: string;
6}
7
8const parentModuleDir = () => {
9 const parts = __dirname.split('/');
10 return parts
11 .reverse()
12 .splice(parts.indexOf('node_modules') + 1, parts.length)
13 .reverse()
14 .join('/');
15};
16
17const toPath = (options: IReadOptions = {}) => {
18 return options.path || fsPath.join(parentModuleDir(), './.env');
19};
20
21/**
22 * Determines whether an .env exists.
23 */
24export function exists(options: IReadOptions = {}) {
25 return fs.existsSync(toPath(options));
26}
27
28/**
29 * Reads in the configuration values if the `.env` file exists.
30 */
31export function read(options: IReadOptions = {}): any {
32 return exists(options) ? dotenv.config({ path: toPath(options) }) : {};
33}
34
35// Load environment by default.
36read();