Skip to content
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

fix: loadImage memleak and performance issue #914

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 8 additions & 9 deletions load-image.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const fs = require('fs')
const { Image } = require('./js-binding')
const { Readable } = require('stream')

const { Image } = require('./js-binding')

let http, https

const MAX_REDIRECTS = 20
Expand All @@ -13,10 +14,12 @@ const REDIRECT_STATUSES = new Set([301, 302])
* @param {object} options Options passed to the loader
*/
module.exports = async function loadImage(source, options = {}) {
// use the same buffer without copying if the source is a buffer
if (Buffer.isBuffer(source) || source instanceof Uint8Array) return createImage(source, options.alt)
// load readable stream as image
if (source instanceof Readable) return createImage(await consumeStream(source), options.alt)
// use the same buffer without copying if the source is a buffer
if (Buffer.isBuffer(source)) return createImage(source, options.alt)
// construct a Uint8Array if the source is ArrayBuffer or SharedArrayBuffer
if (source instanceof ArrayBuffer || source instanceof SharedArrayBuffer) return createImage(Uint8Array.from(source), options.alt)
// construct a buffer if the source is buffer-like
if (isBufferLike(source)) return createImage(Buffer.from(source), options.alt)
// if the source is Image instance, copy the image src to new image
Expand Down Expand Up @@ -68,7 +71,7 @@ function makeRequest(url, resolve, reject, redirectCount, requestOptions) {
if (typeof res.statusCode === 'number' && (res.statusCode < 200 || res.statusCode >= 300)) {
return reject(new Error(`remote source rejected with status code ${res.statusCode}`))
}

consumeStream(res).then(resolve, reject)
} catch (err) {
reject(err)
Expand Down Expand Up @@ -100,11 +103,7 @@ function createImage(src, alt) {

function isBufferLike(src) {
return (
(src && src.type === 'Buffer') ||
Array.isArray(src) ||
src instanceof ArrayBuffer ||
src instanceof SharedArrayBuffer ||
src instanceof Object.getPrototypeOf(Uint8Array)
(src && src.type === 'Buffer') || Array.isArray(src)
)
}

Expand Down
Loading