Automatically Compressing Images With NodeJs

Sharing is Caring

Over the years, I’ve worked on a number of projects where we deal with user or company provided images which are often very large resolutions which take a long time to download on mobile phones or or poor internet connections.

As a result, I’ve made suggestions of using services like which can automatically reduce the size of images with very few problems. Some times, companies aren’t willing to take on a minor SaaS licensing cost so I’ve created some simple code that’s generally good enough.

'use strict'

const compressImages = require('compress-images')

const INPUT_PATH = 'images/**/*.{jpg,JPG,jpeg,JPEG,png,svg,gif}'
const OUTPUT_PATH = 'images/reduced/'

compressImages(INPUT_PATH, OUTPUT_PATH, {compress_force: false, statistic: true, autoupdate: true}, false,
  {jpg: {engine: 'mozjpeg', command: ['-quality', '60']}},
  {png: {engine: 'pngquant', command: ['--quality=20-50']}},
  {svg: {engine: 'svgo', command: '--multipass'}},
  {gif: {engine: 'gifsicle', command: ['--colors', '64', '--use-col=web']}}, function () {}


Make sure that you run npm install compress-images from the project root. This will automatically install the compress-images node module.

Adapting Code for Your Use Case

You will need to adapt this code for your use case which is likely to be replacing new images as they come in. I recommend using a file watcher on an “in box” directory and then having a production or output directory that the code will copy to.

Sharing is Caring