smartmime/ts/index.ts
2024-05-28 12:42:25 +02:00

49 lines
1.5 KiB
TypeScript

import type { Readable } from 'stream';
import * as plugins from './smartmime.plugins.js';
import { binaryMimeTypes } from './binary.js';
// TODO: evaluate where this is actually used
export const supportedFileTypes = ['json', 'html', 'svg', 'jpg', 'ts', 'js'];
export const detectMimeType = async (optionsArg: {
path?: string;
buffer?: Uint8Array;
stream?: Readable;
}): Promise<plugins.fileType.FileTypeResult> => {
if (optionsArg.path) {
return {
mime: plugins.mime.getType(optionsArg.path),
ext: plugins.path.extname(optionsArg.path),
} as plugins.fileType.FileTypeResult;
} else if (optionsArg.buffer) {
return plugins.fileType.fileTypeFromBuffer(optionsArg.buffer);
} else if (optionsArg.stream) {
return plugins.fileType.fileTypeFromStream(optionsArg.stream);
}
};
export const isBinary = async (optionsArg: {
path?: string;
buffer?: Uint8Array;
stream?: Readable;
}) => {
const mimeType = await detectMimeType(optionsArg);
return binaryMimeTypes.includes(mimeType.mime);
};
export const getEncoding = async (optionsArg: {
path?: string;
buffer?: Uint8Array;
stream?: Readable;
}) => {
return (await isBinary(optionsArg)) ? 'binary' : 'utf8';
};
/**
* Synchronous version to get encoding based on the file extension
*/
export const getEncodingForPathSync = (path: string): 'binary' | 'utf8' => {
const mimeType = plugins.mime.getType(path);
return binaryMimeTypes.includes(mimeType) ? 'binary' : 'utf8';
};