I’m using the @aws-sdk/client-s3 npm package to upload and download files to and from my AWS S3 Bucket. The app still works fine and uploads and downloads as expected but I get the following error on my console when I attempt to download a file.
(node:8400) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [TLSSocket]. Use emitter.setMaxListeners() to increase limit
(Use `node --trace-warnings ...` to show where the warning was created)
The app still works fine, but I’m worried about the memory leaks and suspect it’s coming from the @aws-sdk/client-s3 package. If you have fixed this issue please advice on how to take care of the memory leaks.
Here is my code for the s3service
s3Service.js
const {
S3Client,
PutObjectCommand,
GetObjectCommand,
} = require("@aws-sdk/client-s3");
exports.s3Upload = async (file, fileKey) => {
const s3client = new S3Client();
const param = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: fileKey,
Body: file.buffer,
};
return s3client.send(new PutObjectCommand(param));
};
exports.s3DownloadFile = async (fileKey) => {
const s3client = new S3Client({ region: process.env.AWS_REGION });
const param = {
Bucket: process.env.AWS_BUCKET_NAME,
Key: fileKey,
};
try {
return await s3client.send(new GetObjectCommand(param));
} catch (error) {
console.error("Error", error);
}
};
and here’s my route code
/** Import statements */
const express = require("express");
const { s3DownloadFile } = require("../s3Service");
const { Company } = require("../models/companies");
const { Backup } = require("../models/backups");
const router = express.Router();
router.get("/download/:companyName/latest", async (req, res) => {
try {
const company = await Company.findOne({
where: {
companyName: req.params.companyName,
},
});
if (!company)
return res.status(404).send("The specified company does not exist");
const backups = await Backup.findAll({
where: {
companyID: company.dataValues.companyID,
},
order: [["createdAt", "DESC"]],
});
if (backups.length === 0)
return res.status(404).send("There are no backups for this company");
let fileKey = `${company.companyID}/${backups[0].dataValues.fileName}`;
const data = await s3DownloadFile(fileKey);
// Set appropriate headers for the file download
res.attachment(fileKey);
data.Body.pipe(res);
} catch (error) {
res.status(500).send(error.message);
}
});
module.exports = router;