mirror-filecoffee-filehost/engines/local.engine.js

60 lines
1.6 KiB
JavaScript
Raw Permalink Normal View History

2024-06-04 18:45:19 +02:00
const multer = require("multer");
const path = require("path");
const mime = require("mime-types");
const fs = require("fs");
const { nanoid } = require("nanoid");
const initializeLocalStorage = (multerOptions, fileNameLength, uploadPath) => {
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadPath);
},
filename: (req, file, cb) => {
const ext = mime.extension(file.mimetype);
const randomName = nanoid(fileNameLength);
cb(null, `${randomName}.${ext}`);
},
});
const upload = multer({ storage: storage, ...multerOptions });
const writeFile = (req, res, next) => {
upload.single("file")(req, res, (err) => {
if (err) {
return res.status(500).json({ error: err.message });
}
req.filePath = req.file.filename;
next();
});
};
const findFile = (filename, res) => {
const filePath = path.join(uploadPath, filename);
fs.access(filePath, fs.constants.F_OK, (err) => {
if (err) {
return res.status(404).json({ error: "File not found" });
}
res.sendFile(filePath);
});
};
2024-06-09 14:54:28 +02:00
const gatherStatistics = () => {
let totalUploads = 0;
let totalSize = 0;
const files = fs.readdirSync(uploadPath);
files.forEach((file) => {
const filePath = path.join(uploadPath, file);
const stats = fs.statSync(filePath);
totalUploads++;
totalSize += stats.size;
});
return { totalUploads, totalSize };
};
return { writeFile, findFile, gatherStatistics };
2024-06-04 18:45:19 +02:00
};
module.exports = initializeLocalStorage;