Resize Your Image Before Uploading To Your Server or S3 Bucket in NodeJs | JavaScript

Muhammad Asad Attari
1 min readAug 13, 2022

--

Instead uploading a large files to your server which waste storage and create memory issues later on you can resize images before uploading. Here is simple way to resize your images.

Follow these steps to resize image

Step 1: Install NPM Package “sharp”

$ npm i sharp

Step 2: Require or import package

const sharp = require('sharp');

step 3: Different Ways to resize images to different formats

  1. Using Callback
sharp(image)
.resize()
.toFile('output.jpeg', (error, info)=>{
console.log(error);
})

2. Using Promises
If you need binary format then you can convert image to buffer.

let imageBuffer;
sharp(image)
.resize(300,300)
.jpeg()
.toBuffer()
.then((data)=>{
console.log(data);
imageBuffer= data;
})
.catch((err)=>{
console.log(err)
})

Note: Here you may face an issue, because this is asynchronous code so if you use imageBuffer variable after this code then you will get an error because at that time imageBuffer is undefined because sharp will send response later.

Solution: you can use async/await …. put await before sharp

Conclusion:

we looked at how to resize image which will reduce the dimension as well as size of the image, this method is efficient while uploading bundled of images on server. If you have any question, you are always welcome!

--

--

Muhammad Asad Attari
Muhammad Asad Attari

Written by Muhammad Asad Attari

Software Engineer | Full Stack Developer | DevOps Engr.

No responses yet