How to parse Database URLs in NodeJs – Using parse-database-url

Node.js is an open-source JavaScript run time environment that uses the chrome V8 engine to execute JavaScript. It helps us run JavaScript code outside the browser environment enabling it to function as a backend language.

In this technical writing, we will learn how database URLs are parsed in node js.

Every database connection requires specific parameters for configuration, including the driver name, username, password, host, port number, and database name. These variables can be combined in a string and accessed through a single object using the npm package:

parse-database-url

In order to execute the code in this article, you must have NodeJs installed on your device. We will be using the mysql database in this tutorial.

Setting up the environment

Create a folder and redirect your path using the cd <folder_name> command. In the terminal, enter the following command to create the package.json file:

npm init

Follow the instructions in the terminal. Now install the parse-database-url package using the following command:

npm install parse-database-url

Install the dotenv package by entering the following code in the terminal:

npm install dotenv

Install the MySQL package using the following command:

npm install mysql2

This will help install all the relevant dependencies needed for this tutorial.

Code for mysql connection

Make a '.env' file in your project folder and enter the following line of code:

DATABASE_URL=mysql://username:password@localhost:port/DatabaseName

Replace 'username', 'password', 'port' and 'DatabaseName' with your local configuration values.

Make an 'index.js' file, copy the following code into an IDE like VS code, and enter 'node index.js' in the terminal.

import mysql from "mysql2"
import dotenv from "dotenv"
import DbUrl from "parse-database-url"

dotenv.config();
const dbConfig = DbUrl(process.env.DATABASE_URL)
var pool  = mysql.createPool({
connectionLimit : 10,
host            : dbConfig.host,
user            : dbConfig.user,
password        : dbConfig.password,
database        : dbConfig.database
});
 
pool.query('SELECT * FROM todolist', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0]);
});

Output

Database URL parser in NodeJs
Database URL parser in NodeJs

In order to view this output you must set up a mysql database as shown here.

Explanation

  • Line#1โ€“2: We import the 'mysql2' and 'dotenv' packages as module objects named 'mysql' and 'dotenv'.
  • Line#3: We import the 'parse-database-url' package as a module object by the name 'DbUrl'
  • Line#4: The 'config()' method will parse the '.env' file and assign the contents to 'process.env'
  • Line#5: We pass the 'process.env.DATABASE_URL' variable which contains our database URL string to the 'DbUrl()' constructor. This returns an object which is assigned to the 'dbConfig' object.
  • Line#7: We create a connection to the database using the 'createPool()' method and pass it to the 'pool' object.   
  • Line#8โ€“13: Information needed to connect to the database is passed in objects; including 'connectionLimit', 'host', 'user', 'password', and the 'database' to be connected. This information is accessed using the 'dbConfig' object.
  • Line#15โ€“18: In order to test our connection, the 'query()' method is used here to retrieve data from the table 'todolist'. We pass an SQL statement as a string along with a function for error handling. The row of data is returned in a JSON object printed on the terminal (Line#17).

The Final Verdict

Using Dburl() method we are able to reduce the number of environment variables in our project, keeping sensitive information such as database connection details inside the โ€˜.envโ€™ file.ย 

This method does not work for passwords with special characters and non-existent drivers in the โ€˜DATABASE_URLโ€™ string.

Stay in the Loop

Get the weekly email from Algoideas that makes reading the AI/ML stuff instructive. Join our mailing list to stay in the loop to stay informed, for free.

Latest stories

- Advertisement -

You might also like...