Skip to content

Commit

Permalink
Fail fast for Buffer with unsupported format #105
Browse files Browse the repository at this point in the history
  • Loading branch information
lovell committed Oct 28, 2014
1 parent 2e61839 commit a472ade
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 19 deletions.
9 changes: 7 additions & 2 deletions index.js
Expand Up @@ -54,10 +54,15 @@ var Sharp = function(input) {
this.options.fileIn = input;
} else if (typeof input === 'object' && input instanceof Buffer) {
// input=buffer
if (input.length > 0) {
if (
(input.length > 1) &&
(input[0] === 0xff && input[1] === 0xd8) || // JPEG
(input[0] === 0x89 && input[1] === 0x50) || // PNG
(input[0] === 0x52 && input[1] === 0x49) // WebP
) {
this.options.bufferIn = input;
} else {
throw new Error('Buffer is empty');
throw new Error('Buffer contains an unsupported image format. JPEG, PNG and WebP are currently supported.');
}
} else {
// input=stream
Expand Down
25 changes: 15 additions & 10 deletions test/unit/io.js
Expand Up @@ -189,22 +189,27 @@ describe('Input/output', function() {
});

it('Fail when input is empty Buffer', function(done) {
var fail = false;
var failed = true;
try {
sharp(new Buffer(0));
fail = true;
} catch (e) {}
assert(!fail);
failed = false;
} catch (err) {
assert(err instanceof Error);
}
assert(failed);
done();
});

it('Fail when input is invalid Buffer', function(done) {
sharp(new Buffer([0x1, 0x2, 0x3, 0x4]))
.toBuffer(function (err) {
assert.ok(err);
assert.ok(err instanceof Error);
done();
});
var failed = true;
try {
sharp(new Buffer([0x1, 0x2, 0x3, 0x4]));
failed = false;
} catch (err) {
assert(err instanceof Error);
}
assert(failed);
done();
});

it('Promises/A+', function(done) {
Expand Down
7 changes: 0 additions & 7 deletions test/unit/metadata.js
Expand Up @@ -185,11 +185,4 @@ describe('Image metadata', function() {
});
});

it('Report an invalid image as an error', function(done) {
sharp(new Buffer([0x1, 0x2, 0x3, 0x4])).metadata(function (err, metadata) {
assert.ok(err);
assert.ok(err instanceof Error);
done();
});
});
});

0 comments on commit a472ade

Please sign in to comment.