Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

300
Visualizações
Loading environment variables with dotenv still returns undefined

I'm at a loss here. My .env file is in my root directory, as instructed. I've tried this by way of both require('dotenv').config() and import dotenv from 'dotenv', followed by dotenv.config(). I've tried passing config an absolute path, as you will see. Trying to console log the environment variables always returns undefined. I tried checking for dotenv.error, as you will also see, and the condition doesn't trigger.

All I see is undefined. It's as if my .env file doesn't even exist.

Here is my code in its current state. Any help would be appreciated.

import express from "express";
import cors from "cors";
import multer from "multer";
import AWS, { PutObjectCommandOutput, S3, S3ClientConfig } from "@aws-sdk/client-s3";
import { createReadStream } from "fs";
import path from 'path';

const dotenvAbsolutePath = path.join(__dirname, '.env')

const app = express();
const port = 5000;
// require('dotenv').config();
const dotenv = require('dotenv').config({
  path: dotenvAbsolutePath,
});
if (dotenv.error) {
  console.log(`DOTENV ERROR: ${dotenv.error.message}`);
  throw dotenv.error;
}

const keys = {
  key: process.env.AWS_ACCESS_KEY_ID,
  secret: process.env.AWS_SECRET_KEY,
  region: process.env.AWS_REGION
};
console.log(dotenv);

const upload = multer({
  storage: multer.diskStorage({ destination: "./tmp" }),
});

const s3 = new S3({
  credentials: { accessKeyId: keys.key!, secretAccessKey: keys.secret! },
  region: keys.region!
});

app.use(cors());

app.post("/", upload.single("pdf_upload"), async (req, res) => {
  let fileName: string | undefined;
  // let fileBuffer: Buffer | undefined;
  let uploadResponse: PutObjectCommandOutput | undefined;

  if (req.file) {
    fileName = req.file.originalname;
    // fileBuffer = req.file.buffer
    console.log("HTTP Request Received");
    const fileReadStream = createReadStream(req.file!.path).on(
      "ready",
      async () => {
        try {
          console.log("Stream is Readable");
          console.log(fileReadStream.bytesRead);
          uploadResponse = await s3.putObject({
            Bucket: "fiberpunch-test",
            Key: fileName,
            Body: fileReadStream,
          });
          res.header("Access-Control-Allow-Origin", "*");
          res
            .send({ file: { ETag: uploadResponse.ETag, Key: fileName } })
            .status(200);
        } catch (err: any) {
          console.log("Upload Error: ", err.message);
          res.sendStatus(500);
          console.log(fileReadStream.bytesRead);
        }
      }
    );
  }
});

try {
  app.listen(port);
  console.log(`listening at port ${port}`);
} catch (err) {
  console.log("ERROR SETTING UP SERVER");
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I think you need to use process.env to access your env variables. Try logging process.env.AWS_ACCESS_KEY_ID

about 4 years ago · Juan Pablo Isaza Relatório

0

Okay, I figured it out. First of all, I was working in typescript and forgot to compile. Second, the absolute path to the .env file was incorrect. After I did that, the environmental variable pull just fine.

I'm running into a new error, though:

Upload Error:  The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

I'll post another question if I can't figure this one out. Thanks, everyone.

about 4 years ago · Juan Pablo Isaza Relatório

0

If you use AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in your .env file, you don't have to use them again to create a S3 object. AWS automatically recognizes these keys and uses them for S3 object creation. You only need region to create a S3 object.

const s3 = new S3({
  region: 'your region'
});

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda