[英]How to read .env file variables in Nodejs within Azure function
[英].env file not being recognized when trying to read from a file within a folder instead of root in NodeJS
在我的 NodeJS 應用程序中,我在根目錄中有 .env 文件,其中包含以下信息:
NODE_ENV = development
PORT = 3002
#db credentials
dbURL = 'mongodb+srv://username:password@clusterName-0gcm3.mongodb.net/dbName?retryWrites=true&w=majority'
在根目錄中,我還有配置文件 (config.js),它獲取變量:
const dotenv = require('dotenv');
dotenv.config();
module.exports = {
port: process.env.PORT,
dbURL: process.env.dbURL
}
在我再次位於根文件夾中的 App.js 中,我能夠成功讀取該文件並能夠與數據庫連接:
const express = require('express');
const mongoose = require('mongoose');
const { port, dbURL } = require('./config'); //reading the config file and grabbing the vars
const app = express();
app.use(express.json());
//works well!
mongoose.connect(dbURL, { useUnifiedTopology: true, useNewUrlParser: true})
.then(res => {
console.log(`Listening on port ${port}`);
app.listen(port);
})
.catch(err => console.error(err));
現在我正在嘗試編寫一些獨立的腳本來用一些示例數據填充數據庫,並且在該腳本中我試圖單獨連接到數據庫,因為這些腳本將僅使用node <file>
命令執行。 此文件 (dbPopulate.js) 位於 /helper-scripts/ 文件夾中。 腳本如下所示:
const express = require('express');
const mongoose = require('mongoose');
const {port, dbURL} = require('../config'); //attempting to read config.js that calls the .env file
const app = express();
app.use(express.json());
console.log(dbURL, port) //throws undefined for both vars
mongoose.connect(dbURL, { useUnifiedTopology: true, useNewUrlParser: true})
.then(res => {
console.log(`Listening on port ${port}`);
app.listen(port);
})
.catch(err => console.error(err));
只是為了清楚這是我的文件結構:
/.env
/app.js
/config.js
/helper-scripts/dbPopulate.js (culprit)
顯示錯誤日志的更新:
當我獨立執行 dbPopulate.js 時,出現以下錯誤:
$ node dbPopulate.js
undefined undefined
C:\teamSIO\server\node_modules\mongoose\lib\connection.js:582
throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
^
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
at NativeConnection.Connection.openUri (C:\teamSIO\server\node_modules\mongoose\lib\connection.js:582:11)
at Mongoose.connect (C:\teamSIO\server\node_modules\mongoose\lib\index.js:335:15)
at Object.<anonymous> (C:\teamSIO\server\helper-scripts\dbPopulate.js:30:10)
at Module._compile (internal/modules/cjs/loader.js:1123:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1143:10)
at Module.load (internal/modules/cjs/loader.js:972:32)
at Function.Module._load (internal/modules/cjs/loader.js:872:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
我會嘗試使用數組而不是 object。
require('dotenv').config();
const port = process.env.PORT;
dbURL: process.env.dbURL;
module.exports = [
port,
dbURL
];
並使用
const [port, dbURL] = require('./config');
另外,我認為這不是錯誤,但是您的“dbPopulate.js”中確實有兩個點const {port, dbURL} = require('../config');
文件,這可能是你的問題
您已經很久沒有問過了,但也許我的回答會對其他人有所幫助。
當您從目錄helper-scripts
執行node dbPopulate.js
時, function require
將能夠正確加載../config
,但這反過來將無法找到文件.env
因為它希望在同一級別找到它,從文件/目錄層次結構透視圖。
您可以在helper-scripts
中復制.env
(最好不要這樣做),或者從項目的根目錄執行dbPopulate.js
。
當你運行一個節點應用程序時,.env 文件與你正在運行的文件不在同一相對位置,那么你需要為 .env 文件指定正確的路徑。 例如,如果我在同一個項目文件夾位置中有 app.js 和 .env 文件,那么當我執行 node app.js 時,dotenv.config() 將正常工作,因為它的默認路徑是
process.cwd() + '.env'
但是如果說我在 seeder/chat-message-type.seeder.js 中有一個文件,那么要讀取外部的 .env 文件,我必須從一個目錄中取出 go。
const path = require("path")
// have to modify dotenv file path becuase the app is run from seeder folder
dotenv.config({ path: path.join(process.cwd(), "..", ".env") })
這將確保每當我通過運行讀取 .env 文件時
cd seeder
node chat-message-type.seeder.js
它仍然會從 .env 文件加載所有數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.