circuit

Create a Config File for Your JavaScript Project Like a Pro

Why do we need a config file and how to create it?




Modern-day JavaScript frameworks require config files. Config file short form for Configuration file contains a list of initial parameters and settings your project will need to get started.

It could be anything, like a connection string to the database URL in different development environments, language settings, user settings, etc.

However, if something is private or sensitive information, like API key, or Login credentials, it is advisable to put information in the .env file and not in a config file.

One can argue that we can put everything inside different variables and run the application as it is supposed to, but as I said above, developers should try to write clean and good scalable code.

When developing an application, it is always advisable to write clean code that others can understand. Config files help you to achieve just that.

There are three different ways in which you can write your config files. They are as follows-

  1. JSON

  2. YAML

  3. INI

When it comes to developing Javascript applications, developers prefer to write the config files in a JSON format.

Let us create a simple configuration file for our server application written in node with MongoDB database.

Start a new node application and download all the dependencies by typing the command below-

npm init
npm i --save express

Create a config.js file in the root directory of the project. Add the following code into it:

const config = {
 app: {
   port: 3000,
   name: 'myapp'
 },
 db: {
   host: 'localhost',
   port: 27017,
   name: 'db'
 }
};

module.exports = config;

Create a db.js file in the root directory of the project. Add the following code into it:

const mongoose = require('mongoose');
const config = require('./config');

const { db: { host, port, name } } = config;
const connectionString = `mongodb://${host}:${port}/${name}`;
mongoose.connect(connectionString);

Now, add the following code into the app.js file:

// app.js
const express = require('express');
const config = require('./config');

const app = express();
app.listen(config.app.port);
console.log(config.app.name);

The above code is the simplest way to create a config file for your node project. You can now add the complexity by adding more information to the files and using it as per your use case.

The above code makes it easier to read, and all the configuration information is kept in one single file.

One can also install the config package from npm and achieve the same result by reading the documentation, but you can ignore it now if you want.

Thank you for reading the post. I hope you liked it.




Continue Learning