I'm writing code to read arbitrary web resources via HTTP/HTTPS in a Node.js environment, and I'd like to return the content as a string when it's text data, and as a Buffer when it's binary data.
It's clear that anything that starts with text, like text/html, is text data best returned as a string — using the appropriate character encoding, of course, which may be defined explicitly (such as text/html; charset=utf-8), or may not be. Further, any explicit definition of charset would indicate that the content is text, not binary, regardless of the MIME type.
As far as I can tell, almost everything else is binary data. All audio and video formats that I know of are binary, and nearly every image type, with the exception of image/svg+xml. It seems that most application/... types are binary, but with some notable common exceptions like application/json.
Does the following function seem to adequately determine the issue? If not, what notable exceptions might I be missing?
function isBinary(contentType: string): boolean {
let $: string[];
if (/;\s*charset\s*=/i.test(contentType))
return false;
// Remove anything other than MIME type.
contentType = contentType.replace(/;.*$/, '').trim();
if (/^text\//i.test(contentType) || /\+xml$/i.test(contentType))
return false;
else if (($ = /^application\/(.+)/i.exec(contentType)))
return !/^(javascript|ecmascript|json|ld\+json|rtf)$/i.test($[1]);
else
return true;
}