简体   繁体   中英

using dotenv module in nodejs and typescript

i create a file by this name .env :

DATABASE_URL='mongodb://localhost:27017/Fimstan'
SERVER_PORT=3000

now i want to use that in the app.ts for using the SERVER_PORT .

import * as dotenv from 'dotenv';
dotenv.config();

 app.listen(process.env.SERVER_PORT, () => {
  console.log(`Server Run On Port ${process.env.SERVER_PORT}`);
});

but it show me this message in terminal : Server Run On Port undefined

now whats the problem ? how can i use the .env content in my project ???

import express, { Request, Response, NextFunction } from 'express';
import * as dotenv from 'dotenv';
import http from 'http';
import Logger from './core/logger/logger';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import passport from 'passport';
import cors from 'cors';
import redisClient from 'redis';
import path from 'path';
import configuration from './config/index';
import cookieParser from 'cookie-parser';

process.on('uncaughtException', (e) => {
  Logger.error(e);
});

dotenv.config();


const app: express.Application = express();


app.listen(process.env.SERVER_PORT, () => {
  console.log(`Server Run On Port ${process.env.SERVER_PORT}`);
});

app.get('/', (req, res, next) => {
  console.log('Hello')
})

mongoose.Promise = global.Promise;
mongoose.connect(configuration.databaseConfig.url, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true,
});


app.use(cors());
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "public")));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser("SchoolManagerSecretKey"));

First, you need to make sure that you set the important parts correctly for this to work. That is why I will ignore the rest of your imports and app logic. Try to test the solution I described separately to check if this solves your problem.

  1. Make sure that on your root project folder you have the package.json file and .env file.
  2. In the terminal in the path to the root project folder write 'npm i dotenv' (note: it already containing the definitions you required in Typescript).
  3. Now to the files:

    // root/.env

    SERVER_PORT=3000
    
    // root/app.ts
    import dotenv from 'dotenv';
    dotenv.config();
    console.log(`Server Run On Port ${process.env.SERVER_PORT}`);

Also, note that you get the type (string | undefined) when doing an assignment from process.env.variableName. (I am assuming that you are working with the latest versions of node, dotenv and typescript but I don't think there is much if any a difference in older versions).

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