Skip to content

Instantly share code, notes, and snippets.

@mooyoul
Created January 12, 2021 07:30
Show Gist options
  • Save mooyoul/84fc7dd47dd819c2b9ca07eae7206ec7 to your computer and use it in GitHub Desktop.
Save mooyoul/84fc7dd47dd819c2b9ca07eae7206ec7 to your computer and use it in GitHub Desktop.
media_extractor.ts
import { makeTokenizer as makeHTTPTokenizer } from "@tokenizer/http";
import { imageSize } from "image-size";
export class MediaExtractor {
public async peek(url: string) {
const CHUNK_SIZE = 1024 * 64; // 64KByte
try {
const tokenizer = await makeHTTPTokenizer(url, {
initialChunkSize: CHUNK_SIZE * 2, // 128 KByte
minimumChunkSize: CHUNK_SIZE, // 64 KBytes
});
const bytesToRead = Math.min(tokenizer.fileInfo.size!, CHUNK_SIZE);
const buf = Buffer.alloc(bytesToRead, 0x00);
await tokenizer.peekBuffer(buf);
await tokenizer.close();
try {
const image = imageSize(buf);
return {
url,
resolvedUrl: tokenizer.fileInfo.url,
size: tokenizer.fileInfo.size,
type: image.type,
width: image.width,
height: image.height,
orientation: image.orientation,
};
} catch (e) {
// Zero results
return null;
}
} catch (e) {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment