简体   繁体   中英

require process.env in node.js?

I have a .env file and it has

ABC='abc'

and when I do process.env.ABC in my app.js I can get the abc value. How do I require it to be use in my models' files? I do the same thing process.env.ABC in my models file, it got undefined. I assume I have to require it?

You can use dotenv to require the .env file and store in the a variable when you start your app. Once you have this, you can either pass it as a method argument or wrap your models in module.exports = (env) => { return myModel; } module.exports = (env) => { return myModel; }

In express, it would be something like

const env = require('dotenv').config({path: 
'/custom/path/to/your/env'});

app.use((req, res, next) => {
  app.env =  env;
});

Now, you can access the env by passing req to the models and get the env using req.app.get('env')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM