smartmime/ts/index.ts

49 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-05-20 22:57:24 +00:00
import type { Readable } from 'stream';
2023-07-11 22:32:17 +00:00
import * as plugins from './smartmime.plugins.js';
2020-03-04 14:21:44 +00:00
2024-05-20 22:57:24 +00:00
import { binaryMimeTypes } from './binary.js';
2020-03-04 14:21:44 +00:00
2024-05-20 22:57:24 +00:00
// TODO: evaluate where this is actually used
2021-08-10 09:49:39 +00:00
export const supportedFileTypes = ['json', 'html', 'svg', 'jpg', 'ts', 'js'];
2020-03-04 14:21:44 +00:00
2024-05-20 22:57:24 +00:00
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);
}
2020-03-04 14:21:44 +00:00
};
2024-05-20 22:57:24 +00:00
export const isBinary = async (optionsArg: {
path?: string;
buffer?: Uint8Array;
stream?: Readable;
}) => {
const mimeType = await detectMimeType(optionsArg);
return binaryMimeTypes.includes(mimeType.mime);
2021-08-10 09:49:39 +00:00
};
2020-03-04 15:47:15 +00:00
2024-05-20 22:57:24 +00:00
export const getEncoding = async (optionsArg: {
path?: string;
buffer?: Uint8Array;
stream?: Readable;
}) => {
return (await isBinary(optionsArg)) ? 'binary' : 'utf8';
2021-08-10 09:49:39 +00:00
};
2024-05-28 09:52:26 +00:00
/**
* Synchronous version to get encoding based on the file extension
*/
2024-05-28 10:42:25 +00:00
export const getEncodingForPathSync = (path: string): 'binary' | 'utf8' => {
2024-05-28 09:52:26 +00:00
const mimeType = plugins.mime.getType(path);
return binaryMimeTypes.includes(mimeType) ? 'binary' : 'utf8';
};