Brown Limie Brown Limie - 6 months ago 45
Node.js Question

How to use imagemin to compress images and busboy

I want to use the following library to compress images

The problem is when the user uploads using a form, how do I plug in the file details from the form to the image min plugin? Like for example, if the file form field is call example-image, how do I plug that file form field to image min plugin so that it can compress the images?

I tried:

req is from the express/nodejs req

var filebus = new Busboy({ headers: req.headers }),
promises = [];

filebus.on('file', function(fieldname, file, filename, encoding, contentType) {

var fileBuffer = new Buffer(0),

if (file) {
file.on('data', function (d) {
fileBuffer = Buffer.concat([fileBuffer, d]);
}).on('end', function () {
Imagemin.buffer(fileBuffer, {
plugins: [
imageminPngquant({quality: '80'})
}).then(function (data) {
if (s3ImgPath) {
promises.push(this.pushImageToS3(s3ImgPath, data[0].data, contentType));

But the problem is I rather have a buffer of the file that I can upload to S3. I don't want to come the files to a build/images folder. I want to get a buffer for the file, compress it, and upload that buffer to s3. How can I use image min to get a buffer of the file upload via html form and upload that to s3?


The documentation for the output parameter shows that it is optional (though admittedly, the function declaration did not, which might be confusing).


Type: string

Set the destination folder to where your files will be written. If no destination is specified no files will be written.

Therefore, you can opt out of writing the files to storage and just use the output in memory:

imagemin([file.path], {
  plugins: [
      imageminPngquant({quality: '65-80'})
}).then(files => {
  // upload file to S3