Sunday, August 21, 2022

[FIXED] How to add database environment variables to Javascript

Issue

I want to add my database environment variables to a .env file and use that file in my Javascript program in order to create a connection to my database using Node.js.

So here is my database info which I use to create connection with:

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "my password",
  database: "mydatabase"
});

Then I try to check if I am connected to my database using these lines:

(It should print "Connected!").

con.connect(function(err) {   
  if (err) throw err;
  console.log("Connected!");
});

I want to put the first block of code in another file and require that file in my Node.js program.

How should I do this? How should I require the file? Thank you in advance :)


Solution

I suggest using dotenv package.

Taken straight from the readme:

  1. As early as possible in your application, require and configure dotenv.

    require('dotenv').config()

  2. Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

    DB_HOST=localhost DB_USER=root DB_PASS=s1mpl3

  3. Usage (process.env now has the keys and values you defined in your .env file.)

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

NOTE: Make sure your .gitignore has an entry to ignore .env files.



Answered By - Peter
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.