New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Switch to streams, instead of using fixed-size buffer #94
Comments
Hey, guys. If you're interested I've made a module here |
@AshtonRoute that looks pretty good. I'll look into it, as soon as I get some time. |
@netroy |
For anyone looking for a stream-based solution, get this function: async function getStreamImageSize(stream) {
const chunks = []
for await (const chunk of stream) {
chunks.push(chunk)
try {
return sizeOf(Buffer.concat(chunks));
} catch (error) {/* Not ready yet */}
}
return sizeOf(Buffer.concat(chunks));
} Here's a full example code that shows how to use it. Put it in a const url = require('url')
const http = require('https')
const sizeOf = require('image-size')
const imgUrl = 'https://i.imgur.com/O2HfwuZ.jpg'
const options = url.parse(imgUrl)
async function getStreamImageSize(stream) {
const chunks = []
for await (const chunk of stream) {
chunks.push(chunk)
try {
return sizeOf(Buffer.concat(chunks));
} catch (error) {/* Not ready yet */}
}
return sizeOf(Buffer.concat(chunks));
}
http.get(options, async stream => {
console.log(await getStreamImageSize(stream));
}); This is so fast that in my tests it works with the very first chunk. |
@fregante |
Should it stop after the buffer reaches 100kb? Feels like an easy addition in this case |
I would think so. Image size is usually pretty early in the file no? Ideally it would stop reading the stream as soon as it found it. |
The |
Oh, so it does. Didn't look closely enough. I imagine there's a better way than a try/catch on every chunk but that's not too bad. |
Indeed if |
@fregante I agree, that the try/catch block is the only feasible solution. The only other way would be to buffer to a minimum bytesize, where all information should be available, but I guess this also depends on the image type. |
Current implementation uses a fixed length buffer, that causes issues with some JPEGs .. we should switch over to streams.. That'll also make detecting image-size on streaming requests a lot easier.
This'll fix #34 & #37
The text was updated successfully, but these errors were encountered: