Reputation: 35
I'm new to NodeJS and trying to understand the internal working of the system. Normally we create a .env file or some other configuration file to keep and manage secrets. The same environment values can be kept at the system level like using "export" command on mac.
what I'm trying to understand is how NodeJS loads and reads these value when we start the program either from a configuration file or from system itself.
Upvotes: 1
Views: 360
Reputation: 1452
Let me explain how .env is loaded
import dotenv from 'dotenv'
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config({ path: path.join(__dirname, '.env') });
Here is a step-by-step explanation of what's happening in the code:
The dotenv package is imported at the beginning of the script.
The fileURLToPath()
function is imported from the built-in url module. This function is used to convert the current file's URL (import.meta.url) to an absolute file path that can be used by path module.
The __filename variable
is set to the absolute file path of the current file using the fileURLToPath()
function.
The __dirname variable is set to the directory name of the __filename variable using the path.dirname() function from the built-in path module.
dotenv.config()
function is called with an options object that specifies the path to the .env file. The path.join() function is used to join the __dirname variable and the .env filename to get the absolute path to the .env file. The dotenv.config() function then reads the contents of the .env file and adds the environment variables to the process.env object.
Then you can use it like this: process.env.MYENVVARIABLE
Upvotes: 1
Reputation: 24555
You can dig through the NodeJS source code to actually see how the environment is provided to NodeJS, e.g. here through the RealEnvStore
class. As you can see uv_os_getenv
abstracts access to the env depending on the actual operation system.
At least on unix systems uv_os_getenv
uses the environ
variable which basically references all the environment variables that are made available to the node process as you can see here.
Upvotes: 2