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

Friday, December 16, 2022

[FIXED] How does this expression work? "require('dotenv').config();"

 December 16, 2022     config, dotenv, import, node.js, syntax     No comments   

Issue

I saw this expression:

require('dotenv').config();

At the beginning of a server.js file within a NodeJS project. I am just curious to know how does it work and what does it do?

Because almost always I have seen a variable before the require expression line like

 const express = require('express'); 

and afterwards it will be used somehow like

const app = express();

But require('dotenv').config(); looks different and it hasn't been used like the common approach.


Solution

Import Types

When you define a type in the package.json file, it will set that import type for the whole project. require() cannot be used in type module and import cannot be used in type commonJS

Example package.json

{
  "name": "stack",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "type": /* either commonJS or module */
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

after setting the import type here are the examples of both types in action

// if "type": "commonJS"
const package = require('package')

// if "type": "module"
import package from 'package'

'dotenv'

This is the environment variables module to read .env files. Below are the two ways to import it whether you're using type commonJS or module

require('dotenv').config() // commonJS

import {} from 'dotenv/config' // module

works like this...

.env file

TOKEN=THIS_IS_MY_TOKEN

then in a .js file

/* after importing 'dotenv' one of the two ways listed above */

console.log(process.env.TOKEN) // outputs "THIS_IS_MY_TOKEN"

'express'

this is the two ways to import express with either commonJS or module

const express = require('express') // commonJS

import express from 'express' // module

const app = express() // initializes express app

CommonJS vs ES Module

ES modules are the standard for JavaScript, while CommonJS is the default in Node. js. The ES module format was created to standardize the JavaScript module system. It has become the standard format for encapsulating JavaScript code for reuse.



Answered By - gavin
Answer Checked By - Clifford M. (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