Search code examples
javascriptdotenv

How dotenv Package Work With pg.Pool in NodeJS


I've read some code that uses the dotenv package to create configurations. When I read a file that contains PostgreSQL code for Pool, the code looks like this:

const pg = require('pg')
const { Pool } = pg

// This pool was created without completing the pool connection configuration. 
const pool = new Pool()  

However, I see that this pool configuration is written in the.env file. 

#POOL CONFIGURATIONS
PGUSER=username
PGPASSWORD=password
PGHOST=localhost
PGDATABASE=databasename
PGPORT=5432

and .env file is called once in main file :

// main file
require('dotenv').config() 
const express = require('express')

// below is the server

Why is a pool created without passing any configuration objects as arguments? How does it work in the background? I still can't figure this out clearly.

I've tried searching for this behavior, but I haven't found it yet.


Solution

  • When you run

    require('dotenv').config() 
    

    that sets everything in your .env file to be on process.env.*.

    For example, you say PGUSER=username, so now process.env.PGUSER === "username"

    pg.Pool seems to go with those environment variables by default