Для того чтобы тщательно проверить является ли картинкой то, что отдаётся по url, нужно запросить небольшой кусочек данных из начала ответа и проанализировать эти байты библиотекой file-type. Если в коллекции сигнатур file-type
есть такие данные то вызов вернёт MIME type
, если такой сигнатуры нет - будем диагностировать по заголовку content-type
.
Функция getMimeTypeByURL
возвращает MIME type
ресурса.
Вспомогательная функция checkImageByURL
возвращает true
, если ресурс - картинка. checkImageByURL
вернёт null
если при запросе произошла ошибка. checkImageByURL
вернёт true
если ресурс имеет тип image/svg+xml
, так что сделайте более кастомную проверку, если она вам нужна.
const http = require('http');
const https = require('https');
const { URL } = require('url');
const FileType = require('file-type');
(async () => {
const urls = [
'https://random.dog/53d44c97-25bc-4503-9bed-5e9d6bb0e53a.mp4',
'https://cdn.discordapp.com/emojis/774706529609580586.png?v=1',
'https://www.youtube.com/',
'https://cdn.sstatic.net/Sites/ru/img/sprites.svg',
'https://ru.stackoverflow.com/questions/0/'
];
for (const url of urls) {
await checkImageByURL(url);
}
})();
/**
* @param {string} url
* @returns {Promise<boolean | null>}
*/
async function checkImageByURL(url) {
/** @type {boolean | null} */
let isImage = null;
try {
const mimeType = await getMimeTypeByURL(url);
isImage = mimeType?.startsWith('image');
console.log(`url=${url}, mimeType=${mimeType}, isImage=${isImage}`);
} catch (err) {
console.error(err);
console.warn(`url=${url}, mimeType=NULL, isImage=${isImage}`);
}
return isImage;
}
/**
* @param {string} incomingUrl
* @returns {Promise<string | undefined>}
*/
async function getMimeTypeByURL(incomingUrl) {
const url = new URL(incomingUrl);
if (!['http:', 'https:'].includes(url.protocol)) {
throw new Error(`PROTOCOL "${url.protocol}" is not supported...`);
}
/** @type {http.IncomingMessage} */
const responseStream = await new Promise(
(resolve) => (url.protocol === 'https:' ? https : http).get(url, resolve)
);
if (responseStream.statusCode !== 200) {
console.error(`loading fail: ${url}, statusCode=${responseStream.statusCode}`);
throw new Error(`UNHANDLED RESPONSE STATUS ${responseStream.statusCode}`);
}
const responseFileType = await FileType.fromStream(responseStream);
responseStream.destroy();
const responseContentType = responseStream.headers['content-type']?.replace(/;\s*charset=.+$/, '');
return responseFileType
? responseFileType.mime
: responseContentType;
}
Результат в консоли:
url=https://random.dog/53d44c97-25bc-4503-9bed-5e9d6bb0e53a.mp4,
mimeType=video/mp4, isImage=false
url=https://cdn.discordapp.com/emojis/774706529609580586.png?v=1,
mimeType=image/png, isImage=true
url=https://www.youtube.com/,
mimeType=text/html, isImage=false
url=https://cdn.sstatic.net/Sites/ru/img/sprites.svg,
mimeType=image/svg+xml, isImage=true
loading fail: https://ru.stackoverflow.com/questions/0/, statusCode=404
Error: UNHANDLED RESPONSE STATUS 404
at getMimeTypeByURL (/Users/nörbörnën/git/stackoverflow-practice/src/file-type-1/index.js:55:11)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async checkImageByURL (/Users/nörbörnën/git/stackoverflow-practice/src/file-type-1/index.js:28:22)
at async /Users/nörbörnën/git/stackoverflow-practice/src/file-type-1/index.js:16:5
url=https://ru.stackoverflow.com/questions/0/,
mimeType=NULL, isImage=null
Content-Type: image/png
. Но если точно известно, что окончания "правильные" достаточно разобрать адрес(new URL('abc?123')).pathname === 'abc'
, т.к. в примере не окончание, а параметры запроса.