Simple Node JS Resize Image Before Upload using Sharp Multer
Tags: node, webdev, javascript, sharp
Published: 2022-08-05 23:05:00

## Motivation : 
Every time we upload an image to NodeJS server there are a lot of possibility we also need to optimise or resize the image or both that's why I made a simple package to handle both of the operations at same time called sharp-multer.

## Introduction :
**Multer :** Multer is a Express.js middleware which is used for handling multipart/form-data, which is mostly used library for uploading files.
**Sharp :** Sharp high is a speed Node.js module is to convert large images in common formats to smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions.

**Sharp-Multer :** Node js Utilty package to use with Multer as storage engine to optimise images on the fly using Sharp.

## Installation & Configuration:

**1. Create Node JS App**

```
mkdir test-app
cd test-app
npm init
```

**2. Install Modules**
```
npm install express multer --save
npm install sharp --save
npm install sharp-multer --save
```

**3. Create Server.js File and Import Modules**

```javascript
const express = require("express")
const path = require("path")
const multer = require("multer")
const SharpMulter  =  require("sharp-multer");
const app = express()
```
**4. Setup Sharp Multer to handle Images**
   Here we are creating a storage engine for Multer.
_**destination :**_ you can return any directory you want to store the image make sure the directory is created.
**imageOptions :**  we can pass the size height, width for resizing as well as quality and fileformate (jpg,wep,png) to convert the incoming image for optimisation.

```javascript
const storage =  
 SharpMulter ({
              destination:(req, file, callback) =>callback(null, "images"),
              imageOptions:{
			   fileFormat: "jpg",
			   quality: 80,
			   resize: { width: 500, height: 500 },
			     }
	       });
const upload  =  multer({ storage });
```
**5. Create Route with Multer Middleware**

```javascript
app.post("/upload", upload.single("avatar"), async  (req, res)  => {
console.log(req.file);
return  res.json("File Uploaded Successfully!");
}


```

**6. Add HTML file to render the Form**

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title>File Upload</title>
</head>
<body>
    <div class="container">
        <h1>File Upload</h1>
<!--Create a form to send the file to a route  "upload"-->
<!--Set the request method to POST-->
<!--Set the encytype to "multipart/form-data" in order to send files and not just text-->
        <form action="/upload" method="POST" enctype="multipart/form-data">
            <div class="file-field input-field">
              <div class="btn grey">
                <input type="file" name="avatar">
              </div>
            </div>
            <button class="btn" type="submit">Submit</button>
          </form>
    </div>
</body>
</html>
```
**7. Serving File and defining Port**

```javascript
app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '/index.html'));
});


app.listen(3000, () => {
  console.log(`Server is running on port ${3000}`)
})
```

**8. Running the Server**

```
node Server
```
After that you can open your browser and start uploading the images will be automatically optimised and stored in the destination you defined on setting up sharp multer.

For more advance options and watermark check out [next part](https://dev.to/ranjan/resizing-adding-watermark-on-images-with-nodejs-and-sharp-multer-4khp)

Thanks for reading try it out once :smiley: