Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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