Download image buffer from URL
import http from 'http' | |
import https from 'https' | |
import {Transform} from 'stream' | |
const IMAGE_TYPES = { | |
'image/jpeg': 'ffd8ffe0', | |
'image/jpg': 'ffd8ffe1', | |
'image/png': '89504e47', | |
} | |
const {get} = YOUR_URL.startsWith('https') ? https : http | |
get(YOUR_URL).on('response', res => { | |
const data = new Transform() | |
res.on('data', chunk => data.push(chunk)) | |
res.on('end', async () => { | |
const buffer = data.read() | |
const bufferType = buffer.toString('hex', 0, 4) | |
const [mimeType] = Object.entries(IMAGE_TYPES).find(type => type.includes(bufferType)) || [] | |
if (!mimeType) { | |
throw 'Image must be jpeg or png') | |
} | |
console.log(mimeType, buffer) | |
}) | |
}).on('error', error => { | |
throw error | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Накостылял ещё один велосипед для тех, кто не хочет юзать сторонние либы для задачи по скачиванию картинки по урлу, накостылял ещё один велосипед.
Суть проста: передаешь урл изображения в YOUR_URL, далее идет скачивание и в случае если скачался JPG или PNG отдаётся blob