node.js - process.env 不显示 app.js 之外的变量
问题描述
应用程序.js
import koa from 'koa';
import http from 'http';
import logger from 'koa-logger';
import koaBody from 'koa-body';
import dotenv from 'dotenv';
import dotenvExpand from 'dotenv-expand';
const config = dotenv.config();
dotenvExpand(config);
console.log(process.env); // Here I see all data which are in my .env file
import { client } from '@pg'; // Inside this file I doesn't see this , but it still after initializing dotenv
@pg = db/connection/index.js
import { Client } from 'pg';
console.log(process.env.DATABASE_URL, 'fds'); // here I don't see the same ( all variables from .env file are undefined)
export const client = new Client({
connectionString: process.env.DATABASE_URL
});
如果您需要更多信息,请告诉我。注意我在代码片段中的评论,这可能会有所帮助
解决方案
You need to invoke dotenv
in every file you are calling a .env
variable.
import dotenv from 'dotenv';
import { Client } from 'pg';
const config = dotenv.config();
console.log(process.env.DATABASE_URL, 'fds');
If you want to call dotenv
in all your app files without calling it every time then you need to require it when you run your app:
node -r dotenv/config app.js
推荐阅读
- robotframework - 在 Mac Safari 浏览器上执行 Robotscripts 很奇怪
- php - 根据首字母显示“名字”数据
- vba - Excel 宏根据单元格值验证 2 列
- python - 组合数据帧切片时 concat 和 np_r 之间的不同结果
- json - 在 NodeJS 中检索 POST 的响应
- javascript - 在Javascript中处理字符串中所有字母的出现
- javascript - 如何使用plotly / Python / Dash从原点到用户的鼠标坐标绘制一条线
- php - 为什么 $nextRegistration->participants->contains 显示为 false?
- amazon-web-services - AWS Lambda 函数缓存。24小时缓存数据的最佳方式
- jquery - 单击div时如何将特定位置的文本输入文本框