I started down a little bit of a rabbit hole when I wanted to optimize and scale the images on my site. As you can see there are a lot rather large images on my site, which I like the look of. I just don’t like that some of them were greater than 5MB each!
I started out by searching for a basic bulk image processing tool. I wanted something that wasn’t bloated, janky, or broken. It turns out that wasn’t easy for me to find. Instead I found a few node modules that would do what I wanted. First I started using imagemin-mozjpeg - npm, which is great for the optimization piece, and great for jpegs, but I also want to optimize pngs and resize my files. That got me looking further. I ended up settling on sharp, a library that can do all the processing I wanted.
After a bit more poking around I decided to write my own script. It started out very basic, but like most things it began to develop into something slightly more useful and more complicated than when I started.
What I came up with is a command line node.js tool that will optimize and scale png and jpg files and copy other files to the destination directory if requested. This was nice for me, because I just dump all my images and things into my uploads directory so there are some MP3s and PDFs in there as well.
Before processing the images on my site added up to a whopping 38.8MB, I’ve cut it down to less than 25% to 9.1MB.
All in all it was a pretty fun and painless experience. Having never written node before (and little Javascript) there were some bumps, but node’s developers have done a good job of documenting things along the way.
If this is useful to you, please check out the code (and improve it ) on my gist here: A command line image optimizer written in node. · GitHub
Here are some of the resources I used:
- Building command line tools with Node.js - Atlassian Developers
- File System | Node.js v10.7.0 Documentation
- sharp
- commander - npm
- chalk - npm
- Beautiful Free Images & Pictures | Unsplash (where I get many of the pretty images on the site)