<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<div class="container">
<div class="row">
<h2>Image Compress In Node js</h2>
</div>
<div class="row">
<h2>Use as a Middleware in the routes</h2>
</div>
</div>
const { sendResponse } = require("../Lib/ResponseManager");
const compress_images = require("compress-images");
const fs = require('fs');
module.exports = function (req, res, next) {
let input ;
let output;
req.uploadedFiles = [];
for (const file of req.files) {
compress_images(
input = `${req.directoryPath}/${file.filename}`,
output =`${req.directoryPath}/ `,
{ compress_force: false, statistic: true, autoupdate: true },
false,
{ jpg: { engine: "mozjpeg", command: ["-quality", "60"] } },
{ png: { engine: "pngquant", command: ["--quality=20-50", "-o"] } },
{ svg: { engine: "svgo", command: "--multipass" } },
{
gif: {
engine: "gifsicle",
command: ["--colors", "64", "--use-col=web"],
},
},
function (error, completed, statistic) {
if (completed) {
console.log(completed);
console.log(statistic);
console.log("-------------");
req.uploadedFiles.push(` ${file.filename}`);
fs.unlinkSync( file.path )
} else {
console.log("-------------");
console.log(error);
sendResponse(res, 400, error);
}
}
);
}
next();
};