DEV Community

Cover image for Load or set environment variables in Node.js without dotenv or any third package.
Shahrukh Khan
Shahrukh Khan

Posted on

Load or set environment variables in Node.js without dotenv or any third package.

Hello guys, If you are also trapped in the use of dotenv variables then this is for you a complete solution to load/set/manage environment variables in Node.js with the use of javascript & without the burdon of dotenv or any third package.
You can use it in Dev, Prod, UAT or any other environment without any issue.

Step 1: create a server
index.js

const http =require('http');
    const { port, environment } = require('./config').getEnv();

    http.createServer().listen(port, async () => {
      console.log(`env: ${environment}`);
      console.log(`server is running on ${port} port`);
    }).on('error', (e) => console.log(e));
Enter fullscreen mode Exit fullscreen mode

Step 2: configuration of environement variables
config.js

const fs = require('fs');
    const path = require('path');
    const { parseBuffer } = require('./helpers/parse');

    const getEnv = () => {
      const envFilePath = path.join(__dirname, '.env');
      const bufferEnv = fs.readFileSync(envFilePath);
      const envObject = parseBuffer(bufferEnv);

      Object.keys((envObject || {})).map(key => {
        if(!process.env[key] && process.env[key] !== envObject[key]){
          process.env[key] = envObject[key];
        }
      });

      const version = process.env.VERSION;
      const environment = process.env.ENVIRONMENT;
      const port = process.env.PORT;

      return {
        version,
        environment,
        port,
      }
    }

    module.exports = {
      getEnv
    }
Enter fullscreen mode Exit fullscreen mode

Step 3: create .env file & define your variables
.env

VERSION=v1.0.0
ENVIRONMENT=local
PORT=3001
Enter fullscreen mode Exit fullscreen mode

Step 4: A function to parse buffer data into object
parse.js

const NEWLINES_MATCH = /\r\n|\n|\r/
    const NEWLINE = '\n'
    const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/
    const RE_NEWLINES = /\\n/g

    const parseBuffer = (src) => {
      const obj = {};
      src.toString().split(NEWLINES_MATCH).forEach((line, idx) => {
        // matching "KEY" and "VAL" in "KEY=VAL"
        const keyValueArr = line.match(RE_INI_KEY_VAL);
        // matched?
        if(keyValueArr != null){
          const key = keyValueArr[1];

          // default undefined or missing values to empty string

          let val = (keyValueArr[2] || '');
          const end = val.length -1;
          const isDoubleQuoted = val[0] === '"' && val[end] === '"';
          const isSingleQuoted = val[0] === "'" && val[end] === "'";

          // if single or double quoted, remove quotes 
          if(isSingleQuoted || isDoubleQuoted) {
            val = val.substring(1, end);

            // if double quoted, expand newlines
            if(isDoubleQuoted){
              val = val.replace(RE_NEWLINES, NEWLINE);
            }        
          } else {
            //  remove surrounding whitespace
            val = val.trim();
          }
          obj[key] = val;
        }
      });
      return obj;
    }

    module.exports = {
      parseBuffer
    }
Enter fullscreen mode Exit fullscreen mode

Conclusion

Try this to overcome the burdon of dotenv & manage everything on yourbehafe.
If you got any issue during implementation of this code just Click to watch the video of solution

Top comments (0)