smartmime/ts/index.ts

42 lines
1.2 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';
};