While loading the .env
file to pass env values to the getToken.js
script in the cypress root folder throws Cannot find module ‘dotenv’error. I have installed npm install dotenv
. Could someone please advise what I am missing here ? .env
file is available in cypress root folder.
Environment : Windows 10 > git bash /command prompt
const puppeteer = require("puppeteer");
require('dotenv').config({path: '.env'})
const baseURL = process.env.CYPRESS_BASE_URL
const testsUser = process.env.CYPRESS_TESTS_USERNAME
puppeteer
.launch({ headless: true, chromeWebSecurity: false, args: ['--no-sandbox'] })
.then(async browser => {
const page = await browser.newPage();
await page.goto(`${baseURL}/login`);
await page.waitFor(2000);
await page.waitForSelector("input[name=username]");
await page.type("input[name=username]", testsUser , {
delay: 50
});
browser.close();
});
package.json
"scripts": {
"cy:run": "cypress run",
"get-token-main": "node getToken.js && mv tokenData.json cypress/fixtures",
"cy:open-qa": "npm run get-token-main && cypress open"
internal/modules/cjs/loader.js:797
throw err;
^
Error: Cannot find module 'dotenv'
Require stack:
- /e2e/getToken.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15)
at Function.Module._load (internal/modules/cjs/loader.js:687:27)
at Module.require (internal/modules/cjs/loader.js:849:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/e2e/getToken.js:3:16)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/e2e/getToken.js' ]
While trying to run my project I am facing the following error: Error: Cannot find module ‘dotenv’. We are going to Learn about All Possible Solutions So Lets Get Start with This Article.
Contents
- How Error: Cannot find module ‘dotenv’ Occurs?
- How To Solve Error: Cannot find module ‘dotenv’?
- Solution 1: You need to install dotenv
- Conclusion
While trying to run my project I am facing the following error.
Error: Cannot find module 'dotenv'
Or
Error [ERR_MODULE_NOT_FOUND]: Cannot find package ‘dotenv’
So here I am writing all the possible solutions that I have tried to resolve this error.
How To Solve Error: Cannot find module ‘dotenv’?
- How To Solve Error: Cannot find module ‘dotenv’?
To Solve Error: Cannot find module ‘dotenv’ Before using dotenv You need to install dotenv. First of all, open Your terminal and run the following command: npm install dotenv@latest Then, create .env file at the root of your project directory. and Define some Variables: BASE_URL=’https://mysite.com’ Then in your index.js file initialize it just like below: require(‘dotenv’).config(); Now, You can access its variable Like process.env.BASE_URL. And Now Your error is solved. thank You.
- Error: Cannot find module ‘dotenv’
To Solve Error: Cannot find module ‘dotenv’ Before using dotenv You need to install dotenv. First of all, open Your terminal and run the following command: npm install dotenv@latest Then, create .env file at the root of your project directory. and Define some Variables: BASE_URL=’https://mysite.com’ Then in your index.js file initialize it just like below: require(‘dotenv’).config(); Now, You can access its variable Like process.env.BASE_URL. And Now Your error is solved. thank You.
Solution 1: You need to install dotenv
Before using dotenv You need to install dotenv. First of all, open Your terminal and run the following command.
npm install dotenv@latest
Then, create .env file at the root of your project directory. and Define some Variables.
BASE_URL='https://mysite.com'
Then in your index.js file initialize it just like below.
require('dotenv').config();
Now, You can access its variable Like process.env.BASE_URL.
require('dotenv').config();
console.log(process.env.BASE_URL); // OUTPUT: https://mysite.com
And Now Your error is solved. thank You.
Conclusion
It’s all About this error. Hope We solved Your error. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?
Also, Read
- cannot read properties of null (reading ‘addEventListener’)
- A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
- The filename, directory name, or volume label syntax is incorrect
- Module not found: Error: Can’t resolve ‘laravel-vite-plugin/inertia-helper’
- AttributeError: ‘WebDriver’ object has no attribute ‘find_elements_by_xpath’
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:UserscontasourcereposNodeJsDemo1index.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:UserscontasourcereposNodeJsDemo1index.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.
1. Purpose
In this post, I would demonstrate how to solve the following error when trying to start a javascript/react/nodejs application:
➜ controlpanel git:(master) npm start
> [email protected] start
> node scripts/start.js
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module 'dotenv'
Require stack:
- /Users/bswen/WebstormProjects/react-and-redux/chapter-02/controlpanel/scripts/start.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:999:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/bswen/WebstormProjects/react-and-redux/chapter-02/controlpanel/scripts/start.js:7:1)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/Users/bswen/WebstormProjects/react-and-redux/chapter-02/controlpanel/scripts/start.js'
]
}
Node.js v17.1.0
➜ controlpanel git:(master)
2. The solution
Just run this command in the directory containing package.json
:
The npm install installs all modules that are listed on package. json file and their dependencies. npm update updates all packages in the node_modules directory and their dependencies
3. Summary
In this post, I demonstrated how to solve the Cannot find module
error when trying to start an application like reactjs or nodejs, the key point is to install its dependencies by running npm install
. That’s it, thanks for your reading.
The project vite1.0 upgrading to vite2.0 encountered some error, below is finishing some solution:
Warning: Duplicate key «server» in object literal
vite.config.js:67:4: warning: Duplicate key "server" in object literal
67│ │ server: {╵ ~~~~~~ vite.config.js:29:4: note: The original "server" is here
29│ server: {╵Copy the code
Why: There are multiple servers in vite. Config. js
Error: Cannot find module ‘dotenv’
failed to load config from /Users/duoduo/react-new/tianjin-data-web/vite.config.js
error when starting dev server:
Error: Cannot find module 'dotenv'
Require stack:
Copy the code
Install NPM install dotenv
No loader is configured for «.vue»
src/main.ts:19:22: error: No loader is configured for ".vue" files: src/components/v-login-box.vue
19 │ import vLoginBox from "/@/components/v-about.vue"╵ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~Copy the code
Solution: the vite. Config. Js the alias «/ @ /» instead of «@», and global search «/ @ /», replace with «@ /»
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
"public": path.resolve(__dirname, "./public"),}},Copy the code
Error 404: proxy failed to take effect. Add host and POST to server
server: {
port: process.env.VITE_PORT,
// Whether to open automatically in the browser
open: true.
5. Package build images to production environment, font resource path 404
If the problem is not solved, then check whether the image path is placed in public. Static resources must be placed in public
build: {
minify: "esbuild".assetsDir: "".outDir: `./dist/${process.env.VITE_ENV}`,},Copy the code
Finally, put the total vite.config.js configuration
const fs = require("fs");
import path from "path";
I was recently writing some code in Node.js, when I got an unexpected error; ” Cannot find module ‘dotenv’ “. A snippet of the error is given below:
Cannot find module 'dotenv'
I would like to share the steps that helped me to fix the error; Error: Cannot find module ‘dotenv’
Why Error Cannot find module ‘dotenv’ is seen?
The error, Error: Cannot find module ‘dotenv’ is seen because most of the times dotenv is not installed properly in your project file. The error is also caused when there is no proper deployment of the dotenv
A simple solution to fix this would be to install the latest version of dotenv. If you still face the same error, please make sure to restart your IDE and development server. The problem is with VSCode as it often glitches and a reboot solves the problem.
A detailed solution to fix the Error: Cannot find module ‘dotenv’ is provided below:
To fix the error; Error: Cannot find module ‘dotenv’, you will have to install the dotenv
package in the terminal of your project’s root directory and run the command ‘ npm install dotenv’ shown below :
npm install dotenv
After running the code please make sure to restart your IDE and development server.
Here is an example of how the error occurs in your index.js.
require('dotenv').config();
// if you use ES6 you only need this line to import
// import 'dotenv/config'
console.log(process.env.DB_USER);
console.log(process.env.ENV);
console.log(process.env.DB_PORT);
For the next step open the terminal in your project’s root directory or the directory where your package.json
file is located and run the command shown below
npm install dotenv
This step is going to add the dotenv
package into the dependencies in your project.
The above steps should fix the error for most cases.If even after the above steps the error is not resolved; try to restart your IDE and your development server.
The next step would be to try to delete your node_modules
and package-lock.json
; please do not delete the package.json
file. You will have to re-run npm install
and restart your IDE and development server. Follow the code given below:
# delete node_modules and package-lock.json
rm -rf node_modules
rm -f package-lock.json
# clean npm cache
npm cache clean --force
npm install
npm install dotenv@latest
After these steps please make sure to restart your IDE and development server if you still face the same error. The problem is with VSCode as it often glitches and a reboot solves the problem.
Now to launch the dotenv you will have to create a new.env
file in your root directory. You will create a new .env file by following the code mentioned below:
DB_PORT=1234
DB_USER=james_doe
ENV=dev
Do not forget to add the .env
file to your, .gitignore
, This is even more important if you are working on a public repository.
Before you import anything else, import and initialize the dotenv
package In your index.js
file by following the below-mentioned code.
require('dotenv').config();
// if you use ES6 you only need this line to import
// import 'dotenv/config'
console.log(process.env.DB_USER);
console.log(process.env.ENV);
console.log(process.env.DB_PORT);
Your first step should be to load and initialize the dotenv package as the most prioritized thing in your index.js
file, especially if you have other files which require access to the environment variables.
Now the final step would be to restart your development server and then you would be able see the properties on the process.env
object.
Conclusion
To fix the Error: Cannot find module ‘dotenv’ error; use sass instead of node-sass; you would have to install the latest version of dotenv. If you still face the same error, please make sure to restart your IDE and development server.
The problem is with VSCode as it often glitches and a reboot solves the problem. The error is also caused when there is no proper deployment of dotenv. Check the above mentioned steps to know how to deploy dotenv properly.
0 / 0 / 0 Регистрация: 06.06.2017 Сообщений: 53 |
|
1 |
|
16.02.2018, 18:43. Показов 2100. Ответов 6
Захотел написать робота на биржу криптовалюты bitfinex.com. Из языков выбор пал на node.js, поскольку js я более-менее понимаю. Скачал этот фреймворк версии node-v8.9.4-x64. Установил на него требуемые в процессе работы модули, и в какой то момент решил скачать отсюда дистрибутив программы, и попробовать поиграться с примерами. На первом же примере (файл examplesws2cancel_all.js) получил ошибку «Cannot find module ‘dotenv'» (см. скрин). Как я понял, ошибка в файле bfx.js в строке require(‘dotenv’).config(). Запросы типа «npm install dotenv», «npm install dotenv —save», «npm install dotenv —save-dev -cross-env», а также «set NODE_ENV=production» (нагуглено ), и создание файла «.env» в корневой директории проекта не помогли Как мне быть?
__________________
0 |
MrOnlineCoder Всегда онлайн 1082 / 786 / 295 Регистрация: 07.04.2013 Сообщений: 2,703 |
||||
16.02.2018, 19:32 |
2 |
|||
SergMT, как я вижу, bitfinex-api-node это npm пакет, и его можно использовать в своем скрипте, поэтому лучше будет создать новый проект, создать тестовый свой скрипт и установить bitfinex-api-node через npm, который, в свою очередь, установить все необходимые зависимости включая dotenv:
0 |
0 / 0 / 0 Регистрация: 06.06.2017 Сообщений: 53 |
|
19.02.2018, 15:36 [ТС] |
3 |
И всё же не совсем понятно. Миниатюры
0 |
МихаилБасов 28 / 22 / 15 Регистрация: 29.11.2017 Сообщений: 75 |
||||
23.02.2018, 05:40 |
4 |
|||
Bash — скрипт можно запускать в консоли node.js? Ну, вспомним, что платформа написана на си и плюсах, что дает доступ к оп.системе. Добавлено через 7 минут
здесь рекомендуют http://www.nodebeginner.ru/. Достойный ресурс? Только документация достойный ресурс, остальное пережиток документации, лол)) Добавлено через 8 минут
Bash — скрипт можно запускать в консоли node.js? Если да, то этот файл (я назвал его 0.js) выдаёт ошибку (см скрин). Ахахаха, только сейчас понял всю эту трагедию)) Это нужно в консоле выполнить, а не в ноде (или вручную)
0 |
0 / 0 / 0 Регистрация: 06.06.2017 Сообщений: 53 |
|
23.02.2018, 11:03 [ТС] |
5 |
Ахахаха, только сейчас понял всю эту трагедию)) Ну, собственно я и сделал это в консоле node. В уже созданой папке запустил npm init и npm install —save bitfinex-api-node. Так что вопрос всё тот же
При копировании файла в новую директорию, исправлении путей к файлам в require и запуске его получаю ту же ошибку.
0 |
МихаилБасов |
23.02.2018, 16:20
|
Не по теме: Ну, собственно я и сделал это в консоле node. В уже созданой папке запустил npm init и npm install —save bitfinex-api-node. Так что вопрос всё тот же Тогда хз)
0 |
0 / 0 / 0 Регистрация: 06.06.2017 Сообщений: 53 |
|
04.03.2018, 17:31 [ТС] |
7 |
Ну, что может кто-нибудь что-то по существу сказать?
0 |