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");
}
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.