no-shot / env
1 1
import { readFileSync } from "fs";
2 1
import parse from "../parse";
3 1
import assign from "../assign";
4 1
import getFilePath from "../getFilePath";
5 1
import fileExists from "../fileExists";
6 1
import { logMessage, logWarning } from "../log";
7
import type { ConfigOptions, ConfigOutput, ParsedEnvs } from "../index";
8

9
/**
10
 * Extracts and interpolates one or multiple `.env` files into an object and assigns them to {@link https://nodejs.org/api/process.html#process_process_env | `process.env`}.
11
 * Example: 'KEY=value' becomes { KEY: "value" }
12
 *
13
 * @param options - accepts: { `dir`: string, `paths`: string | string[], `encoding`: BufferEncoding, `override`: boolean | string, `debug`: boolean | string }
14
 * @returns a single object with `parsed` and `extracted` Envs as { KEY: "value" } pairs
15
 * @example config({ dir: "example", paths: ".env" });
16
 */
17 1
export function config(options?: ConfigOptions): ConfigOutput {
18
  // default config options
19 1
  let dir: ConfigOptions["dir"] = process.cwd();
20 1
  let paths: ConfigOptions["paths"] = [".env"];
21
  let debug: ConfigOptions["debug"];
22
  let override: ConfigOptions["override"];
23 1
  let encoding: ConfigOptions["encoding"] = "utf8";
24

25
  // override default options with config options arguments
26 1
  if (options) {
27 1
    dir = options.dir || dir;
28 1
    paths = options.paths || paths;
29 1
    debug = options.debug;
30 1
    encoding = options.encoding || encoding;
31 1
    override = options.override;
32
  }
33

34
  // split paths into array of strings
35 1
  const configs = Array.isArray(paths) ? paths : paths.split(",");
36

37
  // initializes parsed Env object
38 1
  const extracted: ParsedEnvs = {};
39

40
  // loop over configs array
41 1
  for (let i = 0; i < configs.length; i += 1) {
42
    // gets config paths file
43 1
    const envPath = getFilePath(configs[i], dir);
44 1
    try {
45
      // checks if "envPath" is a file that exists
46 1
      if (!fileExists(envPath)) throw String("File doesn't exist");
47

48
      // reads and parses Envs from .env file
49 1
      const parsed = parse(readFileSync(envPath, { encoding }), override);
50

51
      // assigns Envs to an accumulated 'extracted' object
52 1
      Object.assign(extracted, parsed);
53

54 1
      if (debug) logMessage(`Loaded env from ${envPath}`);
55
    } catch (err) {
56 1
      if (debug) logWarning(`Unable to load ${envPath}: ${err.toString()}.`);
57
    }
58
  }
59

60 1
  return {
61
    parsed: assign(extracted),
62
    extracted
63
  };
64
}
65

66 1
export default config;

Read our documentation on viewing source code .

Loading