问题
I am trying to access some environment variables using process.env
that were loaded by dotenv
.
My folder structure :
.env
src
-- - server.js
My server.js configuration :
(...)
import auth from './middleware/auth'
import dotenv from 'dotenv'
dotenv.load({
path: '../',
silent: process.env.NODE_ENV === 'production'
})
auth()
// Instantiate app
const app = express();
The file where I try to access process.env
variable :
(...)
module.exports = function() {
console.log("env", process.env.MONGODB_URI)
var options = {};
options.jwtFromRequest = ExtractJwt.fromAuthHeader()
options.secretOrKey = process.env.JWT_SECRET
Which logs env, undefined
, and then crashes with
TypeError: JwtStrategy requires a secret or key
Even if I move .env
into src
(same directory as server) and remove path
in config
, it fails.
回答1:
It appears that when you specify the path, you need to make it full:
require('dotenv').config({path: __dirname + '/../.env'});
.env being your file
回答2:
I'm using require('dotenv').config()
on my main nodejs .js entry file and it works just fine.
From the docs:
Path
Default: .env
You can specify a custom path if your file containing environment variables is named or located differently.
require('dotenv').config({path: '/custom/path/to/your/env/vars'})
回答3:
use may use:
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
USER=sample@gmail.com
PASSWORD=iampassword123
API_KEY=1234567890
some js file from sub-directory
const ck = require('ckey');
const userName = ck.USER; // sample@gmail.com
const password = ck.PASSWORD; // iampassword123
const apiKey = ck.API_KEY; // 1234567890
回答4:
Try this; this should work.
import {} from 'dotenv/config'
import somethingElse from 'somethingElse'
...
[the rest of your code]
This works because of how ES6 modules imports modules.
If you want to dig into more. Please refer this. https://hacks.mozilla.org/2015/08/es6-in-depth-modules/
As a summary :
When you run a module containing an import declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.
Hope this will help someone.
来源:https://stackoverflow.com/questions/42283841/dotenv-not-loading-properly