简体   繁体   English

在 nodejs 和 typescript 中使用 dotenv 模块

[英]using dotenv module in nodejs and typescript

i create a file by this name .env :我用这个名字创建了一个文件.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 .现在我想在app.ts中使用app.ts来使用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但它在终端中向我显示此消息: Server Run On Port undefined

now whats the problem ?现在有什么问题吗? how can i use the .env content in my project ???我如何在我的项目中使用.env内容???

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.确保在您的根项目文件夹上有 package.json 文件和 .env 文件。
  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).在根项目文件夹路径中的终端中写入“npm i dotenv”(注意:它已经包含您在 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.另外,请注意,在从 process.env.variableName 进行赋值时,您会获得类型 (string | undefined)。 (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). (我假设您正在使用最新版本的 node、dotenv 和 typescript,但我认为旧版本没有太大区别)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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