Error: Cannot find module 'dotenv' in NodeJs express

Dung Do Tien May 30 2022 265

Hello Guys, I am studying about NodeJs and I created an example to help read data from .env config file.  And using express help create server, You can see my code here:

index.js

 require('dotenv').config();
var express = require('express');
var app = express();

app.get('/', function (req, res) {
        res.send('Hello Nodejs');
        console.log(process.env.DB_USER);
        console.log(process.env.ENV);
        console.log(process.env.DB_PORT);
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});

.env file

 DB_PORT=2088
DB_USER=local
ENV=development

When I run command node index.js I got an exception throw Error: Cannot find module 'dotenv'.

 Error: Cannot find module 'dotenv'
Require stack:
- C:\Users\conta\source\repos\NodeJs\Demo1\index.js
←[90m    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:965:15)←[39m
←[90m    at Function.Module._load (internal/modules/cjs/loader.js:841:27)←[39m
←[90m    at Module.require (internal/modules/cjs/loader.js:1025:19)←[39m
←[90m    at require (internal/modules/cjs/helpers.js:72:18)←[39m
    at Object.<anonymous> (C:\Users\conta\source\repos\NodeJs\Demo1\index.js:1:1)
←[90m    at Module._compile (internal/modules/cjs/loader.js:1137:30)←[39m
←[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)←[39m
←[90m    at Module.load (internal/modules/cjs/loader.js:985:32)←[39m
←[90m    at Function.Module._load (internal/modules/cjs/loader.js:878:14)←[39m
←[90m    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)←[39m {
  code: ←[32m'MODULE_NOT_FOUND'←[39m,
  requireStack: [ ←[32m'C:\\Users\\conta\\source\\repos\\NodeJs\\Demo1\\index.js'←[39m ]

I really installed dotenvn package in my project before I pushed it on GitHub.

How can I solve this issue? Thank you in advance.

Have 2 answer(s) found.
  • M

    Massimiliano La Puma May 30 2022

    Sometimes I got the same error and I run the commands below and it solved for me:

     # 1. delete node_modules and package-lock.json
    rm -rf node_modules
    rm -f package-lock.json
    
    # 2. clean npm cache
    npm cache clean --force
    
    # 3. re-install dotenv package
    npm install
    npm install [email protected]

    Hope it also work for you.

  • W

    Washington May 30 2022

    If you really installed dotenv package, you can run the command:

      npm install

    If not, run the command:

     npm install dotenv 
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close