PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 21, 2022

[FIXED] How to add database environment variables to Javascript

 August 21, 2022     database, environment-variables, javascript, node.js     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing