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

前端 未结 4 1027
忘掉有多难
忘掉有多难 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 05:06

    node v14.2.0 To set env variable first create a file name config.env in your project home directory and then write all the variables you need, for example

    config.env

    NODE_ENV=development
    PORT=3000
    DATABASE=mongodb+srv://lord:@cluster0-eeev8.mongodb.net/tour-guide?retryWrites=true&w=majority
    DATABASE_LOCAL=mongodb://localhost:27017/tours-test
    DATABASE_PASSWORD=UDJUKXJSSJPWMxw
    

    now install dotenv from npm, dotenv will offload your work

    npm i dotenv
    

    now in your server starter script, in my case it is server.js use doenv to load env variables.

    const dotenv = require('dotenv');
    dotenv.config({ path: './config.env' });
    const app = require('./app'); // must be after loading env vars using dotenv
    
    //starting server
    const port = process.env.PORT || 3000;
    app.listen(port, () => {
      console.log(`app running on port ${port}...`);
    });
    

    I am using express, all my express code in app.js, writing here for your reference

    const express = require('express');
    const tourRouter = require('./route/tourRouter');
    const userRouter = require('./route/userRouter');
    
    if (process.env.NODE_ENV === 'development') {
      console.log('mode development');
    }
    app.use(express.json());
    
    app.use('/api/v1/tours', tourRouter);
    app.use('/api/v1/users', userRouter);
    
    module.exports = app;
    
    

    now start your server using the console, I am using nodemon, you can install it from npm;

    nodemon server.js
    

提交回复
热议问题