How can I set an environmental variable in node.js?

前端 未结 4 1022
忘掉有多难
忘掉有多难 2020-12-24 04:09

How can I set an environmental variable in node.js?

I would prefer not to rely on anything platform specific, such as running export or cmd.exe\'s set.

4条回答
  •  死守一世寂寞
    2020-12-24 04:52

    First you should install this package :- https://github.com/motdotla/dotenv [npm install dotenv]

    Then you need to create a .env file in your project's root directory, and there you can add variables like below:-

    NODE_ENV=PRODUCTION
    DATABASE_HOST=localhost
    

    Now you can easily access these variables in your code like below:-

    require('dotenv').config()
    console.log(process.env.NODE_ENV);
    

    It worked for me, hopefully that helps.

提交回复
热议问题