Build a Batch Image Resizer CLI
A command-line tool that walks a folder of images, resizes each to a target width while preserving aspect ratio, skips files already small enough, and reports before and after sizes.
Project goal
Build a CLI that batch-resizes images to a maximum width, preserves aspect ratio and format, skips images already within the target, writes outputs to a separate directory, and prints a summary of space saved.
Final features
- Recursively discover supported image files and report the count before starting.
- Resize each image to a maximum width without upscaling smaller images.
- Write outputs to a chosen directory, preserving the relative folder structure.
- Skip images already within the target width and log the reason.
- Print a per-file and total summary of bytes saved.
Architecture
A discovery module finds candidate files; a planner decides per file whether to resize based on dimensions; an executor performs the resize and write; and a reporter formats the summary. The image library is wrapped behind a thin adapter so the planner and reporter can be tested without decoding real images.
Prerequisites
- Node.js 20 LTS or later
- Familiarity with streams and binary file handling
- Basic understanding of image dimensions and aspect ratio
Dependencies
- node >=20 — File traversal and the CLI entry point
- sharp ^0.33.0 — Fast image decoding, resizing, and encoding
- vitest ^2.1.0 — Planner and reporter unit tests
Directory structure
image-resizer/
├── src/
│ ├── discover.js
│ ├── planner.js
│ ├── executor.js
│ ├── adapter.js
│ └── cli.js
├── test/
│ ├── planner.test.js
│ └── discover.test.js
└── package.json
Phases
1. File discovery
Recursively walk the input directory and collect image files with supported extensions, ignoring everything else.
Files: src/discover.js
import { readdir, stat } from 'node:fs/promises';
import { join, extname, relative } from 'node:path';
const SUPPORTED = new Set(['.jpg', '.jpeg', '.png', '.webp']);
export async function discover(root) {
const found = [];
async function walk(dir) {
for (const entry of await readdir(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) await walk(full);
else if (SUPPORTED.has(extname(entry.name).toLowerCase())) {
const info = await stat(full);
found.push({ path: full, rel: relative(root, full), sizeBytes: info.size });
}
}
}
await walk(root);
return found;
}Expected behavior: A temporary tree with nested folders yields exactly the supported files with correct relative paths and byte sizes.
2. Resize planner
Decide per image whether to resize or skip, preserving aspect ratio and never upscaling.
Files: src/planner.js
export function planResize(file, targetWidth) {
if (file.width <= targetWidth) {
return { action: 'skip', reason: 'within target', width: file.width, height: file.height };
}
const ratio = targetWidth / file.width;
return {
action: 'resize',
width: targetWidth,
height: Math.max(1, Math.round(file.height * ratio)),
};
}
export function planAll(files, targetWidth) {
return files.map((f) => ({ file: f, plan: planResize(f, targetWidth) }));
}Expected behavior: A wide image plans a resize to exactly the target width, a narrow one plans a skip, and the height is rounded rather than truncated.
3. Image adapter
Wrap the image library behind a minimal interface so tests can substitute fake metadata and the planner never imports it.
Files: src/adapter.js
import sharp from 'sharp';
export function createAdapter() {
return {
async readMetadata(path) {
const meta = await sharp(path).metadata();
return { width: meta.width, height: meta.height, format: meta.format };
},
async resize(path, outPath, width, height) {
await sharp(path).resize({ width, height, fit: 'fill' }).toFile(outPath);
return outPath;
},
};
}Expected behavior: Reading metadata from a tiny fixture returns the real width and height, and a resize call writes a file readable by the same adapter.
4. Executor and output layout
Apply the plan, create output directories mirroring the input tree, and write resized files without overwriting the source.
Files: src/executor.js
import { mkdir } from 'node:fs/promises';
import { dirname, join } from 'node:path';
export async function execute(planned, { adapter, outDir }) {
const results = [];
for (const { file, plan } of planned) {
if (plan.action === 'skip') { results.push({ rel: file.rel, action: 'skip' }); continue; }
const meta = await adapter.readMetadata(file.path);
const target = join(outDir, file.rel);
await mkdir(dirname(target), { recursive: true });
await adapter.resize(file.path, target, plan.width, plan.height);
results.push({ rel: file.rel, action: 'resize', from: meta, to: plan });
}
return results;
}Expected behavior: Executing against a temp output directory creates mirrored subdirectories and never writes back over any input file.
5. CLI surface
Parse input, output, and width arguments, validate them, and support a dry-run flag that prints the plan only.
Files: src/cli.js
import { discover } from './discover.js';
import { planAll } from './planner.js';
import { execute } from './executor.js';
import { createAdapter } from './adapter.js';
const args = parse(process.argv.slice(2));
if (!args.input || !args.width) {
console.error('usage: resize --input <dir> --width <px> [--out out] [--dry-run]');
process.exit(1);
}
const files = await discover(args.input);
const adapter = createAdapter();
const withMeta = [];
for (const f of files) withMeta.push({ ...f, ...(await adapter.readMetadata(f.path)) });
const planned = planAll(withMeta, Number(args.width));
console.log(files.length + ' images found, ' + planned.filter((p) => p.plan.action === 'resize').length + ' to resize');
if (!args.dryRun) {
await execute(planned, { adapter, outDir: args.out ?? 'resized' });
}Expected behavior: Missing --width exits with code 1 and a usage line, and a dry run prints counts without writing any output.
6. Summary reporting and tests
Print a per-file and total summary of bytes saved, and cover discovery, planning, and execution with tests.
Files: src/report.js
export function summarize(results, before) {
let bytesBefore = 0;
let bytesAfter = 0;
for (const r of results) {
bytesBefore += r.sizeBytes ?? 0;
bytesAfter += r.afterBytes ?? r.sizeBytes ?? 0;
}
const saved = bytesBefore - bytesAfter;
return {
files: results.length,
resized: results.filter((r) => r.action === 'resize').length,
skipped: results.filter((r) => r.action === 'skip').length,
savedPercent: bytesBefore ? Math.round((saved / bytesBefore) * 100) : 0,
};
}Expected behavior: A mixed batch reports the correct resized and skipped counts and a saved percentage that matches the summed byte totals.
Testing
Run npx vitest. Planner tests feed fabricated dimension records and assert skip, resize, and no-upscale decisions including the boundary where width equals the target. Discovery tests run against a temporary folder tree and assert supported extensions are found and unsupported ones ignored. One integration test resizes a tiny fixture and asserts the output file exists with the expected width.
Troubleshooting
sharp fails to install on a slim container
Install the platform build dependencies for sharp or pin a version whose prebuilt binaries exist for the target architecture; the failure is a native build issue, not a code issue.
Resized images look stretched
Compute the height from the aspect ratio and pass it explicitly, or use a fit mode that preserves aspect; passing only a width with a distorting fit is the usual cause of stretching.
Output overwrites the source images
Always write to a separate output directory and mirror the relative path; refusing to write into the input tree makes an accidental overwrite impossible.
Deployment
Distribute as a globally installable CLI or run it in a build step. In a CI pipeline, run with --dry-run first to confirm the plan, then execute to write into the build’s static assets directory.
Known limitations
- Orientations stored in EXIF may need an explicit rotate step before resizing, which this project leaves to the adapter.
- Processing is sequential; very large batches benefit from adding a concurrency pool around the executor.
Project overview
Batch image work is a classic example of a task that is tedious by hand, dangerous to get wrong, and simple once the decisions are written down. This project captures those decisions: what counts as an image, when to skip, where output goes, and how to report what changed.
The tool separates a pure planner from the operator that actually resizes, so the interesting logic can be tested on metadata alone rather than on binary fixtures.
The plan is computed entirely from dimensions, which is what makes it testable without decoding a single pixel:
export function planResize(file, targetWidth) {
const { width, height, sizeBytes } = file;
if (width <= targetWidth) {
return { action: 'skip', reason: 'already within target', width, height };
}
const ratio = targetWidth / width;
return {
action: 'resize',
width: targetWidth,
height: Math.round(height * ratio),
estimatedBytes: Math.round(sizeBytes * ratio * ratio),
};
}
Keeping the estimate in the plan lets the reporter show a projected saving before any bytes are written, which is exactly what a dry run needs.
Setup
sharp ships prebuilt binaries for common platforms, so installation is a single npm command; on unusual architectures it may compile from source, which is why the version is pinned.
| Dependency | Version | Why it is here |
|---|---|---|
| node | >=20 | File traversal and the CLI entry point |
| sharp | ^0.33.0 | Fast image decoding, resizing, and encoding |
| vitest | ^2.1.0 | Planner and reporter unit tests |
Create the project and install:
mkdir image-resizer && cd image-resizer
npm init -y
npm install sharp@^0.33.0
npm install -D vitest@^2.1.0
Wire the CLI and the tests in package.json:
{
"name": "image-resizer",
"type": "module",
"scripts": {
"resize": "node src/cli.js",
"test": "vitest run"
}
}
Keep test fixtures tiny (a 40x20 PNG is enough) so the suite stays fast and the repository stays small.
Phase 1: File discovery
Recursively walk the input directory and collect image files with supported extensions, ignoring everything else. Scoped this tightly, the phase ends with a runnable artifact and a test that proves it, so the next one starts from a known-good base.
import { readdir, stat } from 'node:fs/promises';
import { join, extname, relative } from 'node:path';
const SUPPORTED = new Set(['.jpg', '.jpeg', '.png', '.webp']);
export async function discover(root) {
const found = [];
async function walk(dir) {
for (const entry of await readdir(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) await walk(full);
else if (SUPPORTED.has(extname(entry.name).toLowerCase())) {
const info = await stat(full);
found.push({ path: full, rel: relative(root, full), sizeBytes: info.size });
}
}
}
await walk(root);
return found;
}
Acceptance for this phase: A temporary tree with nested folders yields exactly the supported files with correct relative paths and byte sizes.
Phase 2: Resize planner
Decide per image whether to resize or skip, preserving aspect ratio and never upscaling. Scoped this tightly, the phase ends with a runnable artifact and a test that proves it, so the next one starts from a known-good base.
export function planResize(file, targetWidth) {
if (file.width <= targetWidth) {
return { action: 'skip', reason: 'within target', width: file.width, height: file.height };
}
const ratio = targetWidth / file.width;
return {
action: 'resize',
width: targetWidth,
height: Math.max(1, Math.round(file.height * ratio)),
};
}
export function planAll(files, targetWidth) {
return files.map((f) => ({ file: f, plan: planResize(f, targetWidth) }));
}
Acceptance for this phase: A wide image plans a resize to exactly the target width, a narrow one plans a skip, and the height is rounded rather than truncated.
Phase 3: Image adapter
Wrap the image library behind a minimal interface so tests can substitute fake metadata and the planner never imports it. Scoped this tightly, the phase ends with a runnable artifact and a test that proves it, so the next one starts from a known-good base.
import sharp from 'sharp';
export function createAdapter() {
return {
async readMetadata(path) {
const meta = await sharp(path).metadata();
return { width: meta.width, height: meta.height, format: meta.format };
},
async resize(path, outPath, width, height) {
await sharp(path).resize({ width, height, fit: 'fill' }).toFile(outPath);
return outPath;
},
};
}
Acceptance for this phase: Reading metadata from a tiny fixture returns the real width and height, and a resize call writes a file readable by the same adapter.
Phase 4: Executor and output layout
Apply the plan, create output directories mirroring the input tree, and write resized files without overwriting the source. Scoped this tightly, the phase ends with a runnable artifact and a test that proves it, so the next one starts from a known-good base.
import { mkdir } from 'node:fs/promises';
import { dirname, join } from 'node:path';
export async function execute(planned, { adapter, outDir }) {
const results = [];
for (const { file, plan } of planned) {
if (plan.action === 'skip') { results.push({ rel: file.rel, action: 'skip' }); continue; }
const meta = await adapter.readMetadata(file.path);
const target = join(outDir, file.rel);
await mkdir(dirname(target), { recursive: true });
await adapter.resize(file.path, target, plan.width, plan.height);
results.push({ rel: file.rel, action: 'resize', from: meta, to: plan });
}
return results;
}
Acceptance for this phase: Executing against a temp output directory creates mirrored subdirectories and never writes back over any input file.
Phase 5: CLI surface
Parse input, output, and width arguments, validate them, and support a dry-run flag that prints the plan only. Scoped this tightly, the phase ends with a runnable artifact and a test that proves it, so the next one starts from a known-good base.
import { discover } from './discover.js';
import { planAll } from './planner.js';
import { execute } from './executor.js';
import { createAdapter } from './adapter.js';
const args = parse(process.argv.slice(2));
if (!args.input || !args.width) {
console.error('usage: resize --input <dir> --width <px> [--out out] [--dry-run]');
process.exit(1);
}
const files = await discover(args.input);
const adapter = createAdapter();
const withMeta = [];
for (const f of files) withMeta.push({ ...f, ...(await adapter.readMetadata(f.path)) });
const planned = planAll(withMeta, Number(args.width));
console.log(files.length + ' images found, ' + planned.filter((p) => p.plan.action === 'resize').length + ' to resize');
if (!args.dryRun) {
await execute(planned, { adapter, outDir: args.out ?? 'resized' });
}
Acceptance for this phase: Missing –width exits with code 1 and a usage line, and a dry run prints counts without writing any output.
Phase 6: Summary reporting and tests
Print a per-file and total summary of bytes saved, and cover discovery, planning, and execution with tests. Scoped this tightly, the phase ends with a runnable artifact and a test that proves it, so the next one starts from a known-good base.
export function summarize(results, before) {
let bytesBefore = 0;
let bytesAfter = 0;
for (const r of results) {
bytesBefore += r.sizeBytes ?? 0;
bytesAfter += r.afterBytes ?? r.sizeBytes ?? 0;
}
const saved = bytesBefore - bytesAfter;
return {
files: results.length,
resized: results.filter((r) => r.action === 'resize').length,
skipped: results.filter((r) => r.action === 'skip').length,
savedPercent: bytesBefore ? Math.round((saved / bytesBefore) * 100) : 0,
};
}
Acceptance for this phase: A mixed batch reports the correct resized and skipped counts and a saved percentage that matches the summed byte totals.
Testing strategy
Run npx vitest. Planner tests feed fabricated dimension records and assert skip, resize, and no-upscale decisions including the boundary where width equals the target. Discovery tests run against a temporary folder tree and assert supported extensions are found and unsupported ones ignored. One integration test resizes a tiny fixture and asserts the output file exists with the expected width.
The boundary test matters most: an image exactly at the target width must be skipped, because upscaling-free behaviour is where hand-written scripts most often go wrong.
Extending the project
Additional transforms — format conversion, quality tuning, watermarking — are new branches in the planner and new calls in the adapter, without changing discovery or reporting. A concurrency pool wraps the executor when throughput matters, and a manifest file makes reruns incremental.