.env 调用不同文件中的变量
.env calling variables in different files
我有一个存储两个不同变量的 .env 文件:
x=123
y=456
在同一个文件夹中,我还有另外三个文件,下面有一个树:
/folder
/.env
/config.js
/app_setup.js
/match_algo.js
在我的 config.js 文件中,我正在读取 .env 文件中的变量并导出它们:
const dotenv = require('dotenv');
const cfg = {};
dotenv.config({path: '.env'});
cfg.port = process.env.PORT;
cfg.x = process.env.x;
cfg.y = process.env.y;
module.exports = cfg;
在 app.setup.js 文件中,我使用 .env 中的变量 x
:
var firebase = require("firebase");
const Config = require('./config');
var config = {
apiKey: Config.x
};
firebase.initializeApp(config);
module.exports = firebase;
在 match_algo 中,我使用 .env 中的变量 y
来做其他事情:
const Router = require('express').Router;
const Config2 = require('./config');
const router = new Router();
exports.return_match_uid = function return_match_uid() {
var variable2 = Config2.y;
.....
显然,match_algo中的变量y
没有被正确读取。我没有发现我的代码有任何问题。
当你想给dotenv config一个路径时,你需要给正确的路径。不只是 .env
。看到这个
const dotenv = require('dotenv');
const cfg = {};
dotenv.config({path: './folder/.env'});
cfg.port = process.env.PORT;
cfg.x = process.env.x;
cfg.y = process.env.y;
module.exports = cfg;
希望对您有所帮助
我有一个存储两个不同变量的 .env 文件:
x=123
y=456
在同一个文件夹中,我还有另外三个文件,下面有一个树:
/folder
/.env
/config.js
/app_setup.js
/match_algo.js
在我的 config.js 文件中,我正在读取 .env 文件中的变量并导出它们:
const dotenv = require('dotenv');
const cfg = {};
dotenv.config({path: '.env'});
cfg.port = process.env.PORT;
cfg.x = process.env.x;
cfg.y = process.env.y;
module.exports = cfg;
在 app.setup.js 文件中,我使用 .env 中的变量 x
:
var firebase = require("firebase");
const Config = require('./config');
var config = {
apiKey: Config.x
};
firebase.initializeApp(config);
module.exports = firebase;
在 match_algo 中,我使用 .env 中的变量 y
来做其他事情:
const Router = require('express').Router;
const Config2 = require('./config');
const router = new Router();
exports.return_match_uid = function return_match_uid() {
var variable2 = Config2.y;
.....
显然,match_algo中的变量y
没有被正确读取。我没有发现我的代码有任何问题。
当你想给dotenv config一个路径时,你需要给正确的路径。不只是 .env
。看到这个
const dotenv = require('dotenv');
const cfg = {};
dotenv.config({path: './folder/.env'});
cfg.port = process.env.PORT;
cfg.x = process.env.x;
cfg.y = process.env.y;
module.exports = cfg;
希望对您有所帮助