File size: 2,018 Bytes
f0743f4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | const sharp = require('sharp');
/**
* Determines the file type of a buffer
* @param {Buffer} dataBuffer
* @param {boolean} [returnFileType=false] - Optional. If true, returns the file type instead of the file extension.
* @returns {Promise<string|null|import('file-type').FileTypeResult>} - Returns the file extension if found, else null
* */
const determineFileType = async (dataBuffer, returnFileType) => {
const fileType = await import('file-type');
const type = await fileType.fileTypeFromBuffer(dataBuffer);
if (returnFileType) {
return type;
}
return type ? type.ext : null; // Returns extension if found, else null
};
/**
* Get buffer metadata
* @param {Buffer} buffer
* @returns {Promise<{ bytes: number, type: string, dimensions: Record<string, number>, extension: string}>}
*/
const getBufferMetadata = async (buffer) => {
const fileType = await determineFileType(buffer, true);
const bytes = buffer.length;
let extension = fileType ? fileType.ext : 'unknown';
/** @type {Record<string, number>} */
let dimensions = {};
if (fileType && fileType.mime.startsWith('image/') && extension !== 'unknown') {
const imageMetadata = await sharp(buffer).metadata();
dimensions = {
width: imageMetadata.width,
height: imageMetadata.height,
};
}
return {
bytes,
type: fileType?.mime ?? 'unknown',
dimensions,
extension,
};
};
/**
* Removes UUID prefix from filename for clean display
* Pattern: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx__filename.ext
* @param {string} fileName - The filename to clean
* @returns {string} - The cleaned filename without UUID prefix
*/
const cleanFileName = (fileName) => {
if (!fileName) {
return fileName;
}
// Remove UUID pattern: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx__
const cleaned = fileName.replace(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__/i,
'',
);
return cleaned;
};
module.exports = { determineFileType, getBufferMetadata, cleanFileName };
|