[英]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.
尝试测试我单独描述的解决方案,以检查这是否解决了您的问题。
// 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.