From b8ae5c27c664eaf4bf87acce5ea187bc691071d8 Mon Sep 17 00:00:00 2001 From: Yagiz Nizipli Date: Tue, 23 Jan 2024 13:46:26 -0500 Subject: [PATCH] src: add `process.loadEnvFile` and `util.parseEnv` PR-URL: https://github.com/nodejs/node/pull/51476 Reviewed-By: Matteo Collina Reviewed-By: Moshe Atlow Reviewed-By: Geoffrey Booth Reviewed-By: Antoine du Hamel Reviewed-By: Rafael Gonzaga --- doc/api/process.md | 23 ++++++ doc/api/util.md | 30 +++++++ lib/internal/bootstrap/node.js | 1 + lib/internal/process/per_thread.js | 17 ++++ lib/util.js | 13 +++ src/node.cc | 15 +++- src/node_dotenv.cc | 50 +++++++++--- src/node_dotenv.h | 7 +- src/node_process.h | 2 + src/node_process_methods.cc | 37 +++++++++ src/node_util.cc | 13 +++ test/fixtures/dotenv/.env | 1 + test/fixtures/dotenv/basic-valid.env | 1 + test/parallel/test-process-load-env-file.js | 89 +++++++++++++++++++++ test/parallel/util-parse-env.js | 59 ++++++++++++++ typings/internalBinding/util.d.ts | 1 + 16 files changed, 345 insertions(+), 14 deletions(-) create mode 100644 test/fixtures/dotenv/.env create mode 100644 test/fixtures/dotenv/basic-valid.env create mode 100644 test/parallel/test-process-load-env-file.js create mode 100644 test/parallel/util-parse-env.js diff --git a/doc/api/process.md b/doc/api/process.md index a4296b6d974d94..f269e2961d14fe 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -2260,6 +2260,29 @@ process.kill(process.pid, 'SIGHUP'); When `SIGUSR1` is received by a Node.js process, Node.js will start the debugger. See [Signal Events][]. +## `process.loadEnvFile(path)` + + + +> Stability: 1.1 - Active development + +* `path` {string | URL | Buffer | undefined}. **Default:** `'./.env'` + +Loads the `.env` file into `process.env`. Usage of `NODE_OPTIONS` +in the `.env` file will not have any effect on Node.js. + +```cjs +const { loadEnvFile } = require('node:process'); +loadEnvFile(); +``` + +```mjs +import { loadEnvFile } from 'node:process'; +loadEnvFile(); +``` + ## `process.mainModule` + +* `content` {string} + +The raw contents of a `.env` file. + +* Returns: {Object} + +Given an example `.env` file: + +```cjs +const { parseEnv } = require('node:util'); + +parseEnv('HELLO=world\nHELLO=oh my\n'); +// Returns: { HELLO: 'oh my' } +``` + +```mjs +import { parseEnv } from 'node:util'; + +parseEnv('HELLO=world\nHELLO=oh my\n'); +// Returns: { HELLO: 'oh my' } +``` + ## `util.promisify(original)`