何时在 NodeJS 应用程序中加载 .env 变量?

问题描述

我正在使用 TypeScript 编写一个简单的 NodeJS Express REST API。我有一些使用 dotenv 加载的环境变量。

我在代码的两个不同阶段访问我的 .env 变量:index.ts(我的起始文件)和 MyControllerClass.ts 文件。要访问这些变量,代码process.env.MY_ENV_VAR。要为应用程序加载它们,代码dotenv.config()

由于我的 index.ts 文件似乎是我程序的根目录(我在其中配置了我的应用程序),因此我使用 dotenv.config() 为程序的其余部分加载我的 .env 文件.但是,在我的 MyControllerClass.ts 文件中,在构造函数中,如果我执行 console.log(process.env.MY_ENV_VAR),我会得到“undefined”。我可以通过在我的构造函数添加一个 dotenv.config()解决这个问题(它可以工作),但在这里放置它对我来说是无稽之谈。

如何在我的程序中以可读的方式(例如在适当的 .ts 文件中)一劳永逸地使用 dotenv.config()?更一般地说:什么是 NodeJS Express 加载周期?

这是我的代码文件结构示例

src
├── index.ts
├── Authentication
│   └── authentication.router.ts
│   └── authentication.controller.ts

这里是 index.js 的代码

/**
 * required External Modules
 */
 import * as dotenv from "dotenv";
 import express from "express";
 import cors from "cors";
 import helmet from "helmet";
 import { authenticationRouter } from "./authentication/authentication.router"

 dotenv.config();

 /**
 * App Variables
 */
 if(!process.env.PORT) {
    process.exit(1);
}
const PORT: number = parseInt(process.env.PORT as string,10);
const app = express();

/**
 *  App Configuration
 */
 app.use(helmet());
 app.use(cors());
 app.use(express.json());
 app.use(authenticationRouter);

 app.use("api/authenticate/",authenticationRouter);
/**
 * Server Activation
 */
 app.listen(PORT,() => {
    console.log(`Listening on port ${PORT}`);
  });

这里是authentication.router.ts的代码

import express,{ Request,Response } from "express";
import { AuthenticatorController } from "./authentication.controller";
export const authenticationRouter = express.Router();
const authenticatorController = AuthenticatorController.getInstance();

authenticationRouter.post("/api/authenticate",async (req: Request,res: Response) => {   
    try {
        if (await authenticatorController.authenticate(req.body.login,req.body.password)) {
            res.send({"status": "ok"})
        } else
            res.send({"status": "Error"})
    } catch (e) {
        console.debug(e)
        res.send({"status": "500"});
    }
    
});

这里是authentication.controller.ts的代码

import { ClientSecretCredential } from "@azure/identity";
import { SecretClient } from "@azure/keyvault-secrets";
import { Authenticator } from "./api/Authenticator";
import * as dotenv from "dotenv";
dotenv.config();

export class AuthenticatorController implements Authenticator {
    
    private static singleInstance: AuthenticatorController | null = null;
    private azureSecretCredential= new ClientSecretCredential(
        process.env.AZURE_TENANT_ID as string,process.env.AZURE_CLIENT_ID as string,process.env.AZURE_CLIENT_SECRET as string);
    private azureSecretClient = new SecretClient(
        process.env.KEY_VAULT_URL as string,this.azureSecretCredential);

    private constructor () {}

    public static getInstance(): AuthenticatorController {
        if (this.singleInstance === null) {
            this.singleInstance = new AuthenticatorController();
        }
        return this.singleInstance;
    }

    public async authenticate(login: string,password: string): Promise<Boolean> {
        let isAuthenticated = false;

        try {
            const secret = await this.azureSecretClient.getSecret(login)
            if (secret.name === login) {
                if (secret.value === password) {
                    isAuthenticated = true;
                }
            }
        }   catch (e) {
            console.debug(e);
        }
            return isAuthenticated;
    }
}

解决方法

您只调用 dotenv.config() 一次:

尽早在您的应用程序中,要求和配置 dotenv。

require('dotenv').config()

因此 index.ts 似乎是正确的,然后 process.env 应该保存您的解析值。也许您可以使用这样的方法来确保正确解析数据:

const result = dotenv.config();

if (result.error) {
  throw result.error;
}

console.log(result.parsed);

编辑:

您可以尝试以下操作。我稍微更改了您的导出,因为您的控制器中不需要单例。

authentication.router.ts:

// Imports (no dotenv; no dotenv.config())
// [...]

// Import controller
import { authenticatorController } from "./authentication.controller";

export const authenticationRouter = express.Router();

// Adding routes
// [...]

authentication.controller.ts:

// Imports (no dotenv; no dotenv.config())
// [...]

class AuthenticatorController implements Authenticator {
  // [...]
}

export const authenticatorController = new AuthenticatorController();

index.ts:

// Imports (dotenv)
// [...]

const { error,parsed } = dotenv.config();

if (error) {
  throw error;
}

console.log(parsed);

// [...]

 app.use("api/authenticate/",authenticationRouter);

// [...]