Replacing files in place
Sometimes you want to optimize files in place — no _timestamp copies, no
separate output directory. That’s what --replace is for, and it’s designed to
be safe.
Basic usage
Section titled “Basic usage”imgsqz photo.jpg --replace -q 80This re-encodes photo.jpg and writes the smaller result back to photo.jpg.
How it stays safe (atomic writes)
Section titled “How it stays safe (atomic writes)”A naive “overwrite in place” is dangerous: if the process dies mid-write, you’re left with a truncated, corrupt file. imgsqz avoids this:
- Encode the optimized image to a temporary file next to the target:
photo.jpg.imgsqz.tmp. - Once the temp file is fully written, atomically rename it over the
original (
fs.rename).
A rename is atomic on a single filesystem, so at no point is photo.jpg a
half-written file. If imgsqz is interrupted before step 2, your original is
untouched — you just have a stray .imgsqz.tmp you can delete.
Replacing while converting
Section titled “Replacing while converting”--replace keeps the file in place but the extension follows the format. If you
convert, you get a new file alongside the original name pattern:
# Re-encode and keep as JPG, in placeimgsqz photo.jpg --replace -q 78
# "Replace" but convert to webp → writes photo.webp (the .jpg still exists)imgsqz photo.jpg --replace -f webpBatch replace
Section titled “Batch replace”--replace works across many inputs (unlike --output):
# Optimize every JPG in placeimgsqz *.jpg --replace -q 80 --quietThis is the canonical “shrink this whole folder of photos in place” command.
Replace vs. the alternatives
Section titled “Replace vs. the alternatives”| Goal | Command |
|---|---|
| Keep original, make a timestamped copy (default) | imgsqz photo.jpg |
| Keep original, clean output name | imgsqz photo.jpg --no-timestamp -o photo-opt.jpg |
| Overwrite the original in place | imgsqz photo.jpg --replace |
| Write to a separate folder | imgsqz photo.jpg -o out/photo.jpg |
Next: the full CLI reference.