You've probably been using the dotenv package to load environment variables into your Node.js applications. It's been the go-to solution for many developers. But guess what? Node.js 20 has introduced a nifty feature that lets you load your .env file directly using the --env-file flag. Let's dive into how this works!
With Node.js 20, you can now load your environment file directly when starting your application. Here's how you do it:
node --env-file .env main.jsThis command tells Node.js to load the variables from your .env file into the process environment. It's a straightforward and clean way to manage your environment variables without relying on external packages.
One thing to watch out for is that if your .env file doesn't exist, Node.js will throw an error. But don't worry, there's a way to handle this gracefully. You can use the --env-file-if-exists flag:
node --env-file-if-exists=.env main.jsThis flag ensures that your application won't crash if the .env file is missing. It's a handy option for environments where the file might not always be present.
Need to load multiple environment files? Node.js 20 has you covered. You can specify multiple --env-file flags like this:
node --env-file=.env --env-file=.dev.env main.jsThis command will load variables from both .env and .dev.env files, allowing you to manage different configurations for different environments easily.
Node.js 20 introduces the --env-file flag to load environment variables directly from a file, eliminating the need for external packages like dotenv. Use --env-file-if-exists to avoid errors if the file is missing, and you can load multiple files by specifying multiple --env-file flags.