Skip to content

Instantly share code, notes, and snippets.

@kaenova
Last active October 9, 2023 15:12
Show Gist options
  • Save kaenova/eaf31b59aeb1b18a9c65cd04f437f1f2 to your computer and use it in GitHub Desktop.
Save kaenova/eaf31b59aeb1b18a9c65cd04f437f1f2 to your computer and use it in GitHub Desktop.
A middleware for automatically remove temporary multer middleware files after the response is close
import { unlinkSync } from "node:fs"
import { Request, Response, NextFunction } from "express"
async function temporaryFileRemoverMiddleware(
req: Request,
res: Response,
next: NextFunction,
) {
async function asyncUnlink(path: string) {
unlinkSync(path);
}
// After res is closed
res.on('close', () => {
// Removing on req.file
if (typeof req.file != 'undefined') {
let file = req.file;
asyncUnlink(file.path).catch(() =>
log.error(`Failed to remove ${file.path}`),
);
}
// Removing req.files
const files = req.files;
if (typeof files != 'undefined') {
// On Express.Multer.File[]
if (Array.isArray(files)) {
files.forEach((file) => {
asyncUnlink(file.path).catch(() =>
console.log(`Failed to remove ${file.path}`),
);
});
} else {
// On { [fieldname: string]: Express.Multer.File[] }
let keys = Object.keys(files);
keys.forEach((key) => {
let keyFiles = files[key];
if (Array.isArray(keyFiles)) {
keyFiles.forEach((file) => {
asyncUnlink(file.path).catch(() =>
console.log(`Failed to remove ${file.path}`),
);
});
}
});
}
}
});
next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment