简体   繁体   中英

in nodejs app how to use dotenv and config?

I am new to development, i understand that dotenv create environment variables that we don't want to expose in our code , while config create similar variables to be used by app for configuration however I am little confused about use case. could you explain it a little or point me to further resource for better understanding. and is there any other similar packages that create environment variables and how are they used ?

You can use dotenv npm package for this use case

create a .env file in your project something similar to:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

then you can configure your file:

const dotenv = require('dotenv');
dotenv.config({ path: path.resolve(__dirname, './config.env') })

then you can use them like:

db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

The way I do it is using both dotenv and config packages.

You'd create a .env file (which you'll add to .gitignore)

For example

client_id='1234'
client_secret='XXXXX'

Then you create a folder called config at the root of your project, and inside it a file default.js

In this file you'll add first

require('dotenv').config();

and then you can export js friendly variables

require('dotenv').config(); 

export const client = {
    clientId: process.env.client_id,
    clientSecret: process.env.client_secret
}

Finally you can use these in your index.ts for example

import config from 'config';

console.log(config.get('client'));
// { clientId: '1234', clientSecret: 'XXXXX'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM