dotenv 文件未加载环境变量

发布于 2025-01-11 06:20:32 字数 752 浏览 0 评论 0原文

我在 root 文件夹 文件中有 .env 文件

NODE_ENV=development
NODE_HOST=localhost
NODE_PORT=4000
NODE_HTTPS=false
DB_HOST=localhost
DB_USERNAME=user
DB_PASSWORD=user

,在 root/app/config/server.js 文件夹中有 server.js 文件。 server.js 文件的第一行是

require('dotenv').config();

我还尝试了以下操作:

require('dotenv').config ({路径: '../.env'});

require('dotenv').config({path: '../../.env'});

但是,当我运行 server.js 文件时,我的环境变量没有加载 从命令提示符

node root/app/config/server.js

如果我使用Visual Studio并按F5 ,它加载了!

我不确定我做错了什么,我错过了什么。 任何建议都将受到高度赞赏。谢谢。

I have .env file at root folder file

NODE_ENV=development
NODE_HOST=localhost
NODE_PORT=4000
NODE_HTTPS=false
DB_HOST=localhost
DB_USERNAME=user
DB_PASSWORD=user

And server.js file in the root/app/config/server.js folder.
The first line of server.js file is

require('dotenv').config();

I also tried following:

require('dotenv').config({path: '../.env'});

require('dotenv').config({path: '../../.env'});

However, my env variable are not loaded when I run the server.js file
from command prompt

node root/app/config/server.js

If I use the visual studio and press F5, it loads!!

I'm not sure what I'm doing wrong, what I'm missing.
Any suggestion is highly appreciate. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

没企图 2025-01-18 06:20:32

使用 require('dotenv').config({path:__dirname+'/./../../.env'}) 怎么样?

你的问题似乎是执行路径。

How about use require('dotenv').config({path:__dirname+'/./../../.env'}) ?

Your problem seems to be the execution path.

又爬满兰若 2025-01-18 06:20:32

这解决了我在 Node v8.14.1 中的问题:

const path = require('path')
require('dotenv').config({ path: path.resolve(__dirname, '../.env') })

简单地执行

require('dotenv').config({path:__dirname+'/./../../.env'})

会导致一个位置解析为

/some/path/to/env/./../../.env

This solved my issues in Node v8.14.1:

const path = require('path')
require('dotenv').config({ path: path.resolve(__dirname, '../.env') })

Simply doing

require('dotenv').config({path:__dirname+'/./../../.env'})

resulted in a location that resolved as

/some/path/to/env/./../../.env
绝不服输 2025-01-18 06:20:32

这是一个单行解决方案:

require('dotenv').config({ path: require('find-config')('.env') })

这将递归父目录,直到找到要使用的 .env 文件。

您还可以使用这个名为 ckey 的模块,其灵感来自于一行多于。

主目录中的 .env 文件。

# dotenv sample content
[email protected]
PASSWORD=iampassword123
API_KEY=1234567890

子目录中的一些js文件

const ck = require('ckey');

const userName = ck.USER;     // [email protected]
const password = ck.PASSWORD; // iampassword123
const apiKey   = ck.API_KEY;  // 1234567890

Here is a single-line solution:

require('dotenv').config({ path: require('find-config')('.env') })

This will recurse parent directories until it finds a .env file to use.

You can also alternatively use this module called ckey inspired from one-liner above.

.env file from main directory.

# dotenv sample content
[email protected]
PASSWORD=iampassword123
API_KEY=1234567890

some js file from sub-directory

const ck = require('ckey');

const userName = ck.USER;     // [email protected]
const password = ck.PASSWORD; // iampassword123
const apiKey   = ck.API_KEY;  // 1234567890
我家小可爱 2025-01-18 06:20:32

如果您从嵌套文件调用 dotenv,并且您的 .env 文件位于项目根目录,则您想要连接这些点的方式是通过以下方式:

require('dotenv').config({path:'relative/path/to/your/.env'})

If you are invoking dotenv from a nested file, and your .env file is at the project root, the way you want to connect the dots is via the following:

require('dotenv').config({path:'relative/path/to/your/.env'})
灰色世界里的红玫瑰 2025-01-18 06:20:32

@DavidP 的答案中的评论之一记录了 dotenv.config 的输出,

console.log(require("dotenv").config())

这将输出配置日志并显示错误。就我而言,它表明配置方法正在引用当前目录而不是
包含我的 .env 文件的父目录。我可以通过以下内容进行参考

require('dotenv').config({path: '../.env'})

One of the comments in @DavidP's answer notes logging the output of dotenv.config with

console.log(require("dotenv").config())

This will output a log of the config and display errors. In my case it indicated the config method was referencing the current directory instead of the
parent directory which contained my .env file. I was able to reference that with the following

require('dotenv').config({path: '../.env'})
梦里°也失望 2025-01-18 06:20:32

我遇到了这个问题,结果发现 REACT 只加载以 REACT_APP_ 为前缀的变量

VueJs 可能有类似的问题,因为它期望变量以以下前缀: VUE_APP_

I've had this problem and it turned out that REACT only loads variables prefixed with REACT_APP_

VueJs can have a similar issue as it expects variables to be prefixed with: VUE_APP_

七度光 2025-01-18 06:20:32

确保在入口文件的开头加载.env(例如index.jsserver.js)。有时,执行顺序会在服务启动后加载环境变量。并且,通过使用__dirname,它可以轻松地指向相对于当前文件所需的文件。

这里我的项目结构是这样的。

.
├─ src
│  └─ index.ts
└─ .env
// index.ts
import dotenv from 'dotenv';
import path from 'path';

dotenv.config({path: path.join(__dirname, '..', '.env')});

...

Be sure to load .env at the beginning of the entry file (e.g. index.js or server.js). Sometimes, the order of execution loads the environment variables after the services are initiated. And, by using __dirname, it can easily point to the file required relative to the current file.

Here my project structure is like this.

.
├─ src
│  └─ index.ts
└─ .env
// index.ts
import dotenv from 'dotenv';
import path from 'path';

dotenv.config({path: path.join(__dirname, '..', '.env')});

...
茶底世界 2025-01-18 06:20:32

在您到达到目前为止的远程情况下,我的问题相当愚蠢:
我错误地用冒号“:”而不是等于“=”命名了我的环境变量。菜鸟错误,但结果是没有加载拼写错误的变量赋值。

# dotenv sample content

# correct assignment
[email protected]

# wrong assignment (will not load env var)
USER : [email protected]

In the remote case that you arrive till this point, my issue was quite dumber:
I wrongly named my env variables with colon ":" instead of equals "=". Rookie mistake but the resulting behavior was not loading the misspelled variables assignment.

# dotenv sample content

# correct assignment
[email protected]

# wrong assignment (will not load env var)
USER : [email protected]
玻璃人 2025-01-18 06:20:32

您可以首先使用以下方法进行调试:

console.log(require('dotenv').config())

在我的场景中,我的 .env 文件位于根目录中,我需要在嵌套目录中使用它。结果给了我:

{
  parsed: {
    DATABASE_URL: 'mongodb://localhost/vidly',
    PORT: '8080'
  }
}

所以我简单地解析结果并将其存储在一个变量中:

const dotenv = require('dotenv').config().parsed;

然后像 JS 对象一样访问我的 DATABASE_URL:

dotenv.DATABASE_URL

You can first debug by using:

console.log(require('dotenv').config())

In my scenario, my .env file is in root directory and I need to use it in a nested directory. The result gives me:

{
  parsed: {
    DATABASE_URL: 'mongodb://localhost/vidly',
    PORT: '8080'
  }
}

So I simply parse the result and store it in a variable:

const dotenv = require('dotenv').config().parsed;

Then access my DATABASE_URL like a JS object:

dotenv.DATABASE_URL
鸩远一方 2025-01-18 06:20:32

这为我解决了这个问题:

const path = require('path');
require('dotenv').config({
  path: path.resolve('config.env'),
});

This solved the issue for me:

const path = require('path');
require('dotenv').config({
  path: path.resolve('config.env'),
});
尛丟丟 2025-01-18 06:20:32

试试这个:

const dotenv = require('dotenv');
dotenv.config({ path: process.cwd() + '/config/config.env' });

对我有用,不知道怎么样?

Try this:

const dotenv = require('dotenv');
dotenv.config({ path: process.cwd() + '/config/config.env' });

worked for me idk how??

戴着白色围巾的女孩 2025-01-18 06:20:32
  const path = require('path');
  const dotenv = require('dotenv');
  dotenv.config({ path: path.resolve(__dirname, '../config.env') })
  const path = require('path');
  const dotenv = require('dotenv');
  dotenv.config({ path: path.resolve(__dirname, '../config.env') })
独自唱情﹋歌 2025-01-18 06:20:32

这让我有些头疼,将 require 语句的输出记录到控制台的提示非常有用。 console.log(require('dotenv').config());

结果我是用 nodemon application_name/. 从我的 user/ 目录运行我的应用程序,那就是让 dotenv 在我的主目录而不是应用程序的目录中查找 .env 文件。我很懒,跳过了一张cd,这花了我几分钟的时间。

It took me a few head scratches, and the tip to log the output of the require statement to console was really helpful. console.log(require('dotenv').config());

Turns out I was running my app from my user/ directory with nodemon application_name/. and that was making dotenv look for the .env file in my home dir instead of the app's. I was lazy by skipping one cd and that cost me a few minutes.

梦幻的心爱 2025-01-18 06:20:32

我发现在配置中发送了一个选项 debug: true

dotenv.config({ debug: true });

,它向我显示了以下内容:

[dotenv][DEBUG] "PORT" is already defined in `process.env` and was NOT overwritten

我添加了 overwrite: true 并使其正常工作:

[dotenv][DEBUG] "PORT" is already defined in `process.env` and WAS overwritten

我知道我可能为时已晚回答,但在检查文档几个小时后决定分享我的发现。

I found an option debug: true to be sent in the config

dotenv.config({ debug: true });

which showed me the following:

[dotenv][DEBUG] "PORT" is already defined in `process.env` and was NOT overwritten

I added overwrite: true and got it working:

[dotenv][DEBUG] "PORT" is already defined in `process.env` and WAS overwritten

I know I might be too late answering, but decided to share my findings after hours of checking the documentation.

故事与诗 2025-01-18 06:20:32

我在 Windows 中遇到 .env 文件的编码问题。它采用 UTF-16LE 编码。该文件已被解析,但被认为是空的。在我将 .env 文件转换为 UTF-8 后,一切都按预期工作。

I had a problem with the file encoding of the .env file in windows. It was encoded in UTF-16LE. The file was parsed but it was considered empty. After i converted the .env file to UTF-8 everything works as expected.

咽泪装欢 2025-01-18 06:20:32

就我而言,.env 读起来很好,但 .env.local 则不然。

更新 package.json.env 命名为 .env.local ( cp ./.env.local .env)解决了问题:

  "myscript": "cp ./.env.local .env && node ./scripts/myscript.js"

In my case .env was read fine, but not .env.local.

Updating package.json to name .env into .env.local ( cp ./.env.local .env) solved the problem:

  "myscript": "cp ./.env.local .env && node ./scripts/myscript.js"
倾城花音 2025-01-18 06:20:32

如果 config.env 文件和 index.js 文件都存在于同一目录中:

然后,文件:index.js

const path = require('path'); 

//  Set port from environment variables
dotenv.config({path: 'config.env'})
const PORT = process.env.PORT || 8080

文件:config.env:

PORT = 4000

if config.env file and index.js file both present in the same directory:
enter image description here

then, file: index.js

const path = require('path'); 

//  Set port from environment variables
dotenv.config({path: 'config.env'})
const PORT = process.env.PORT || 8080

file: config.env:

PORT = 4000
歌枕肩 2025-01-18 06:20:32

如果您安装了 dotenv 作为生产依赖项。那么,它可能无法正常工作。 .env 文件通常在开发期间使用 dotenv 将环境变量导入应用程序环境时使用。所以,

npm install --save-dev dotenv

并非如此:

npm install dotenv

要使 dotenv 库正常工作,您始终需要提及该代码:

import dotenv from "dotenv"
dotenv.config();

在文件的 Top 中,如下所示:

在此处输入图像描述

如果你把这个配置放在中间。然后,您将看到一些有线行为。就像,在某些文件 env 变量工作文件中。但在某些情况下,情况并非如此。

If you are installed dotenv as production dependency. Then, it may not work properly. The .env file is commonly utilized during development when using dotenv to import environment variables into the application's environment. So,

npm install --save-dev dotenv

Not that:

npm install dotenv

To working properly of dotenv library, you always need to mention that code:

import dotenv from "dotenv"
dotenv.config();

In Top of the file like this:

enter image description here

If you put that configuration in the middle. Then, you will see some wired behavior. Like, in some file env variable working file. But, in some, it is not.

狼亦尘 2025-01-18 06:20:32

从 Node 版本 20.6.0 开始,您不再需要使用 dotenv 包,因为该功能现已内置。

假设您的目录中有一个 .env 文件,如下所示:

NODE_ENV=development
NODE_HOST=localhost
NODE_PORT=4000
NODE_HTTPS=false
DB_HOST=localhost
DB_USERNAME=user
DB_PASSWORD=user

您可以使用 --env- 轻松将 .env 文件中的变量设置为环境变量file 标志:

node --env-file .env index.js

设置后,这些环境变量可以作为 process.env 的属性进行访问:

console.log(process.env.NODE_ENV);
console.log(process.env.NODE_HOST);

运行该命令将产生以下输出:

// Output
development
localhost

Starting from Node version 20.6.0, you no longer need to use the dotenv package as the functionality is now built-in.

Assuming you have a .env file in your directory like this:

NODE_ENV=development
NODE_HOST=localhost
NODE_PORT=4000
NODE_HTTPS=false
DB_HOST=localhost
DB_USERNAME=user
DB_PASSWORD=user

You can easily set the variables in the .env file as environment variables using the --env-file flag:

node --env-file .env index.js

Once set, these environment variables can be accessed as properties of process.env:

console.log(process.env.NODE_ENV);
console.log(process.env.NODE_HOST);

Running the command will produce the following output:

// Output
development
localhost
你的心境我的脸 2025-01-18 06:20:32

您可能需要 .env 文件相对于启动应用程序的当前工作目录的路径。
您可以像这样创建此路径:

const path = require('path')
require('dotenv').config({path: path.relative(process.cwd(), path.join(__dirname,'.env'))});

process.cwd() 返回工作目录的绝对路径。
__dirname 返回应用程序的绝对路径。
path.join() 将 .env 文件的路径添加到应用程序的路径中。因此,如果您的 .env 文件嵌套得更深,只需添加文件夹(例如 path.join(__dirname, 'config', 'secret','.env'))
path.relative() 创建相对路径。

You can need the path of the .env file relative to the current working directory from where the application was launched.
You can create this path like this:

const path = require('path')
require('dotenv').config({path: path.relative(process.cwd(), path.join(__dirname,'.env'))});

process.cwd() returns the absolute path of the working directory.
__dirname returns the absolute path of the application.
path.join() adds the path of the .env-file to the path of the application. so if your .env file is nested deeper, just add the folders (e.g. path.join(__dirname, 'config', 'secret','.env'))
path.relative() creates the relative path.

赴月观长安 2025-01-18 06:20:32

打字稿。

如果您尝试解析 __dirname 并在另一个文件夹中编译源文件夹,请确保编辑 __dirname。就我而言,我在 dist 文件夹中编译 ts,并且 env 文件不位于 dist 文件夹中,而是位于根文件夹中。所以你应该从 __dirname 中删除 /dist。要调试它,您可以调用 error() 函数,如果读取 env 文件出现问题,该函数将返回错误。

require('dotenv').config({
    path:  __dirname.replace('\dist','') + `${process.env.NODE_ENV}.env`
  }); # To debug .error()

另一件事,当您设置环境变量时,请确保以下内容:
变量和 (&&) 之间没有空格,如下所示

  "scripts": {
    "build": "npx tsc",
    "start": "set NODE_ENV=production&& node dist/index.js",
  },

Typescript.

if you are trying to resolve __dirname and you are compiling your source folder in another folder, make sure that you edit __dirname. in my case i am compiling ts in dist folder and env files are not located in dist folder, but in the root folder. so you should delete /dist from __dirname. To debug it, you can call error() function which returns error if there is problem with reading env file.

require('dotenv').config({
    path:  __dirname.replace('\dist','') + `${process.env.NODE_ENV}.env`
  }); # To debug .error()

another thing, when you set env variables make sure that following:
no space between variable and (&&) as following

  "scripts": {
    "build": "npx tsc",
    "start": "set NODE_ENV=production&& node dist/index.js",
  },
罪歌 2025-01-18 06:20:32

直到我最终添加 override: true

这是我的完整代码

const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../.env'), override: true })

Nothing worked for me until I finally added override: true

Here is my full code

const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../.env'), override: true })
是你 2025-01-18 06:20:32

有一次我也遇到了同样的问题。 Dotenv 未加载 .env 文件。我尝试使用路径配置来解决此问题,将 .env 文件放在根文件夹中,将 .env 放在文件运行的文件夹中,但没有任何帮助。然后我只是删除了 Node_modules 文件夹,重新安装所有依赖项,它就可以正常工作了

One time I have got the same problem. Dotenv did not load .env file. I tried to fix this problem with a path config, to put .env file in a root folder, to put .env in the folder where the file is running and nothing helps me. Then I just trashed Node_modules folder, reinstall all dependencies and it works correctly

不…忘初心 2025-01-18 06:20:32

我正在使用:

import findUp from 'find-up';
dotenv.config({ path: findUp.sync('.env') });

I'am using:

import findUp from 'find-up';
dotenv.config({ path: findUp.sync('.env') });
半城柳色半声笛 2025-01-18 06:20:32

使用 Playwright / typescript 对我有用的方法:

1 创建文件并将其放置在项目的根目录中:global-setup.ts
里面添加:

async function globalSetup() {
  // Configure ENV variables
  require('dotenv').config()
}

export default globalSetup

2 然后将此文件使用到 playwright.config.ts

,如下: globalSetup: require.resolve('./global-setup'),

这样,全局conf 已创建,并在每个测试中进行拾取。

What worked for me using Playwright / typescript:

1 create file and place at the root of the project: global-setup.ts
add inside:

async function globalSetup() {
  // Configure ENV variables
  require('dotenv').config()
}

export default globalSetup

2 Then use this file into playwright.config.ts

as: globalSetup: require.resolve('./global-setup'),

In this way, global conf is created, and pickup in every single test.

一张白纸 2025-01-18 06:20:32

对于 ES6,你需要这样做:

import * as dotenv from 'dotenv';
import * as path from 'path';

dotenv.config({ path: path.join(__dirname, '..', '.env.testing') });

For ES6 you need to do this way:

import * as dotenv from 'dotenv';
import * as path from 'path';

dotenv.config({ path: path.join(__dirname, '..', '.env.testing') });
安穩 2025-01-18 06:20:32

如果您使用其他工具(全局安装)在某处调用您的配置文件,则仅使用绝对路径...

require('dotenv').config({
  path: '/path/to/my/project/.env',
});

Use only absolute path if you are using some other tool(installed globally) to call your config file somewhere ...

require('dotenv').config({
  path: '/path/to/my/project/.env',
});
菊凝晚露 2025-01-18 06:20:32

如何防止 vite.js 在源代码中暴露 env 变量

这是 proccess.env 访问 .env 变量的配置

import path from 'path';
import dotenv from 'dotenv';
import fs from 'fs';
// specify the adress of .env file
const envPath = path.resolve(__dirname, './.env');
// Load environment variables from .env file and put them in proccess.env
dotenv.config({ path: envPath });

斜体文本

  • 防止意外将 env 变量泄漏到客户,
    只有以 VITE_ 为前缀的变量才会暴露给您的 Vite 处理代码。
    例如,对于以下环境变量:
VITE_SOME_KEY=123
DB_PASSWORD=foobar

只有 VITE_SOME_KEY 将公开为 import.meta.env.VITE_SOME_KEY

  • 如果您想公开一个无前缀的变量,您可以使用 Define 来公开它:
    define: {
        "import.meta.env.APP_URL": process.env.APP_URL ? JSON.stringify(
            process.env.APP_URL
        ) : null,
        "import.meta.env.API_BASE_URL": process.env.API_BASE_URL ? JSON.stringify(
            process.env.API_BASE_URL
        ) : null,
        "import.meta.env.CLIENT_URL": process.env.CLIENT_URL ? JSON.stringify(
            process.env.CLIENT_URL
        ) : null,
    },

https://vitejs.dev/config/shared-options.html#envprefix

**请注意,如果您使用以下代码,它会公开源代码中的所有变量:

const envConfig = dotenv.parse(fs.readFileSync(envPath));
    define: {
        'process.env': {
            ...envConfig
        }
    }

how prevent exposing env variables in the source code by vite.js

this is a config for acces .env variable by proccess.env

import path from 'path';
import dotenv from 'dotenv';
import fs from 'fs';
// specify the adress of .env file
const envPath = path.resolve(__dirname, './.env');
// Load environment variables from .env file and put them in proccess.env
dotenv.config({ path: envPath });

Italic Text

  • To prevent accidentally leaking env variables to the client,
    only variables prefixed with VITE_ are exposed to your Vite-processed code.
    e.g. for the following env variables:
VITE_SOME_KEY=123
DB_PASSWORD=foobar

Only VITE_SOME_KEY will be exposed as import.meta.env.VITE_SOME_KEY

  • If you would like to expose an unprefixed variable, you can use define to expose it:
    define: {
        "import.meta.env.APP_URL": process.env.APP_URL ? JSON.stringify(
            process.env.APP_URL
        ) : null,
        "import.meta.env.API_BASE_URL": process.env.API_BASE_URL ? JSON.stringify(
            process.env.API_BASE_URL
        ) : null,
        "import.meta.env.CLIENT_URL": process.env.CLIENT_URL ? JSON.stringify(
            process.env.CLIENT_URL
        ) : null,
    },

https://vitejs.dev/config/shared-options.html#envprefix

**note that if you use the following code it expose all variable in youre source code:

const envConfig = dotenv.parse(fs.readFileSync(envPath));
    define: {
        'process.env': {
            ...envConfig
        }
    }
蘑菇王子 2025-01-18 06:20:32

在 .env 文件中使用“=”定义键值,不要使用冒号“:”

例如下面是不正确的

USER:root

这是在 .env 文件中定义 env 变量的正确方法

USER =根

In .env file use "=" to define key value do not use colon ":"

For example below is incorrect

USER:root

This is correct way to define env variables in .env file

USER=root

尹雨沫 2025-01-18 06:20:32

我的失败是路径关键字。应该是 P 而不是大写字母。太有趣了

My failer was the path keyword . should be the P not capital Letter . that was so funny

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文