Allow toBuffer to resolve Promise with info+data #143

This commit is contained in:
Lovell Fuller
2017-03-04 22:15:31 +00:00
parent 679ce08998
commit 6fe5b307b1
5 changed files with 89 additions and 23 deletions

View File

@@ -48,17 +48,24 @@ const toFile = function toFile (fileOut, callback) {
* JPEG, PNG, WebP, and RAW output are supported.
* By default, the format will match the input image, except GIF and SVG input which become PNG output.
*
* `callback`, if present, gets three arguments `(err, buffer, info)` where:
* - `err` is an error message, if any.
* - `buffer` is the output image data.
* `callback`, if present, gets three arguments `(err, data, info)` where:
* - `err` is an error, if any.
* - `data` is the output image data.
* - `info` contains the output image `format`, `size` (bytes), `width`, `height` and `channels`.
* A Promises/A+ promise is returned when `callback` is not provided.
* A Promise is returned when `callback` is not provided.
*
* @param {Object} [options]
* @param {Boolean} [options.resolveWithObject] Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`.
* @param {Function} [callback]
* @returns {Promise<Buffer>} - when no callback is provided
*/
const toBuffer = function toBuffer (callback) {
return this._pipeline(callback);
const toBuffer = function toBuffer (options, callback) {
if (is.object(options)) {
if (is.bool(options.resolveWithObject)) {
this.options.resolveWithObject = options.resolveWithObject;
}
}
return this._pipeline(is.fn(options) ? options : callback);
};
/**
@@ -423,11 +430,15 @@ const _pipeline = function _pipeline (callback) {
return new Promise(function (resolve, reject) {
that.on('finish', function () {
that._flattenBufferIn();
sharp.pipeline(that.options, function (err, data) {
sharp.pipeline(that.options, function (err, data, info) {
if (err) {
reject(err);
} else {
resolve(data);
if (that.options.resolveWithObject) {
resolve({ data: data, info: info });
} else {
resolve(data);
}
}
});
});
@@ -435,11 +446,15 @@ const _pipeline = function _pipeline (callback) {
} else {
// output=promise, input=file/buffer
return new Promise(function (resolve, reject) {
sharp.pipeline(that.options, function (err, data) {
sharp.pipeline(that.options, function (err, data, info) {
if (err) {
reject(err);
} else {
resolve(data);
if (that.options.resolveWithObject) {
resolve({ data: data, info: info });
} else {
resolve(data);
}
}
});
});