This article is intended to be a short invesitgation into environment variables for myself, hence the terse style
In node, environment variables are accessed via the global process.env
console.log(process.env.USER); // username
There are a few ways we can make these variables available to our programs.
Pretty straightforward — just call the command with the variable in the command line.
DB_CONNECTION="postgresql://username:password@host:port/database_name" node index.js
.env files consist of KEYS and VALUES which are separated by an equals sign.
DB_CONNECTION="postgresql://username:password@host:port/database_name"
These files are commmon, and there are a few ways to make them available to your application.
Use a tool like direnv which loads variables from a file makes them available in the shell; it is this is typically installed globally.
By default direnv looks for a .envrc file, but it can use .env as well, see here for configuring it to do so.
Use a tool like dotenv which loads variables from a file and makes them available in process.env.
There are pros and cons for each method.
Using direnv is language agnostic and means one less dependency, but it also means that consumers of your application need their own way to load environment variables if not using direnv;
Using dotenv ensures that consumers of the application can just use a .env file with no worries, but it does add a package just to do something the shell can do natively.
Node recently included support (v20.6.0) for using .env files directly.
A flag has to be used
node --env-file=.env index.js
Like dotenv, this makes the content of .env available in process.env.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3