Last active
October 9, 2023 15:12
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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