From 00d614a106d214955269e889e6e29b7389d9ef32 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 25 Feb 2024 21:48:30 -0600 Subject: [PATCH] Add Load And Use Env Var In Node Script as a JavaScript TIL --- README.md | 3 +- .../load-and-use-env-var-in-node-script.md | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 javascript/load-and-use-env-var-in-node-script.md diff --git a/README.md b/README.md index 85babff..dd3d878 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1379 TILs and counting..._ +_1380 TILs and counting..._ --- @@ -465,6 +465,7 @@ _1379 TILs and counting..._ - [ISO-8601 Formatted Dates Are Interpreted As UTC](javascript/iso-8601-formatted-dates-are-interpreted-as-utc.md) - [Link A JavaScript Package Locally](javascript/link-a-javascript-package-locally.md) - [List Top-Level NPM Dependencies](javascript/list-top-level-npm-dependencies.md) +- [Load And Use Env Var In Node Script](javascript/load-and-use-env-var-in-node-script.md) - [Make The Browser Editable With Design Mode](javascript/make-the-browser-editable-with-design-mode.md) - [Matching A Computed Property In Function Args](javascript/matching-a-computed-property-in-function-args.md) - [Matching Multiple Values In A Switch Statement](javascript/matching-multiple-values-in-a-switch-statement.md) diff --git a/javascript/load-and-use-env-var-in-node-script.md b/javascript/load-and-use-env-var-in-node-script.md new file mode 100644 index 0000000..7bd5f7c --- /dev/null +++ b/javascript/load-and-use-env-var-in-node-script.md @@ -0,0 +1,43 @@ +# Load And Use Env Var In Node Script + +The node scripts defined under `scripts` in a `package.json` file can be used +to do all sorts of handy development tasks for a project. + +There are times where those scripts would be even more useful if they had +access to environment variables specified in the project's `.env` files. + +With the help of [`dotenv-cli`](https://github.com/venthur/dotenv-cli) and +[`cross-var`](https://github.com/elijahmanor/cross-var), we can load in and +reference the project's env vars. + +As an example, let's say our `.env` file has a `DATABASE_URL`: + +``` +DATABASE_URL="postgresql://postgres:postgres@localhost:5432/postgres" +``` + +We can create a node script in `package.json` that accesses that value like so: + +```json +{ + "scripts": { + "db:url": "dotenv cross-var -- echo \"%DATABASE_URL%\"" + } +} +``` + +Running that command will echo out the value: + +```bash +❯ npm run db:url + +> db:url +> dotenv cross-var -- echo "%DATABASE_URL%" + +postgresql://postgres:postgres@localhost:9876/postgres +``` + +You could do something more useful with that value like open a `psql` +connection to that local database. + +[source](https://www.genui.com/resources/env-variables-json)