Buffer in, WebP out.
Call transcode(buffer, { format: 'webp', maxBytes }) before writing storage.
Build the same output tree from Node. Batches, buffers, transforms, budgets, cache, and explicit failures — all typed.
npm install --save-dev pixelpress
import { optimize, transcode } from 'pixelpress';
Requires Node.js 22.5+. Type declarations ship with the package. The cache is off by default in the API; the CLI enables it.
Process files, directories, or globs. Every path in the result is absolute. Processing continues after a single file fails unless failFast is set.
import { optimize } from 'pixelpress';
const report = await optimize(
['public/images', 'static/**/*.png'],
{
outDir: 'dist/images',
preset: 'web',
formats: ['avif', 'webp', 'jpeg'],
widths: [480, 960, 1920],
quality: { avif: 50, webp: 72 },
include: ['*.jpg', '*.png'],
exclude: ['*-draft.*'],
recursive: true,
cache: true,
cacheDir: 'node_modules/.cache/pixelpress',
prune: true,
lqip: true,
concurrency: 8,
},
);
console.log(report.totals.savedPercent, '% smaller');
console.log(report.totals.cached, 'files reused');
for (const file of report.files) {
for (const variant of file.outputs) {
console.log(variant.format, variant.path, variant.width, variant.bytes);
}
}
Explicit options override a preset. prune requires cache: true. Use failFast to stop after the first failure, or inspect report.failed and keep the successful files.
{
options: { outDir, preset, formats, widths, quality, ... },
files: [
{
input: '/abs/public/images/hero.jpg',
width: 2400,
height: 1600,
sourceBytes: 1436544,
cached: false,
placeholder: 'data:image/webp;base64,...', // --lqip
dominantColor: '#6c7a89', // --lqip
outputs: [
{
format: 'avif',
path: '/abs/dist/images/hero-480.avif',
width: 480,
height: 320,
bytes: 14210,
quality: 55,
animated: false,
pages: 1,
},
],
},
],
skipped: [],
failed: [],
pruned: [],
pruneErrors: [],
totals: {
files: 1,
outputs: 1,
cached: 0,
pruned: 0,
pruneErrors: 0,
sourceBytes: 1436544,
outputBytes: 14210,
savedBytes: 1422244,
savedPercent: 99,
skipped: 0,
failed: 0,
durationMs: 342,
},
}
For a manifest with srcset strings and relative paths, use the CLI's --manifest or build from this result.
Encode one image from a path, Buffer, or Uint8Array. Useful for upload handlers and serverless jobs. The same transforms, format tuning, and size budget apply.
import { transcode } from 'pixelpress';
import { writeFile } from 'node:fs/promises';
const { data, info } = await transcode('upload.jpg', {
format: 'avif',
width: 800,
quality: 50,
maxBytes: 90_000,
grayscale: false,
keepMetadata: false,
});
await writeFile('upload.avif', data);
// info: { format, width, height, bytes, quality, animated, pages,
// sourceWidth, sourceHeight }
For animated inputs, WebP preserves frames; AVIF/JPEG/PNG return the first frame. maxBytes performs a quality search and throws if the variant cannot fit.
The option names match the CLI flags. The full table lives in the CLI reference; the machine-readable schema is at pixelpress.schema.json.
| Group | Options |
|---|---|
| Run | outDir, formats, preset, widths, recursive, flat, include, exclude, followSymlinks, concurrency, dryRun, cache, cacheDir, prune, force, failFast, clean, preserveDates |
| Resize | width, height, fit, position, enlarge |
| Transform | rotate, autoOrient, flip, flop, grayscale, blur, sharpen, normalize, gamma, tint, trim, extract, extend, density |
| Encode | quality, effort, lossless, progressive, chromaSubsampling, alphaQuality, palette, compressionLevel, maxBytes, background, keepMetadata |
| Naming | prefix, suffix, hash |
| Derived assets | lqip |
| Hooks | hooks.beforeEncode, hooks.afterEncode (API and JS config only) |
Presets: web, thumb, social, lossless. Explicit options override them. Quality and effort objects merge with preset values.
API and JS-config only. beforeEncode receives the sharp pipeline before encoding — mutate it or return a replacement. afterEncode receives the final bytes and can return a Buffer to replace them. Hooks are part of the cache fingerprint.
const report = await optimize(['public/images'], {
outDir: 'dist/images',
formats: ['webp'],
hooks: {
beforeEncode: (pipeline) => pipeline.composite([
{ input: 'assets/mark.png', gravity: 'southeast' },
]),
},
});
Per-file failures appear in report.failed as { input, error }. Successful files still land. Newly created outputs for a failed multi-format file are rolled back; outputs that existed before the run are kept.
--fail-fast / failFast: true stops after the first failure. A prune deletion failure appears in pruneErrors and keeps the old cache so the next run can retry. The CLI exits 1 on any failure.
const report = await optimize(['uploads'], {
outDir: 'dist/uploads',
formats: ['webp'],
cache: true,
});
if (report.failed.length) {
for (const item of report.failed) {
console.error(item.input, item.error);
}
process.exitCode = 1;
}
Declarations are included. Main types: OptimizeOptions, OptimizeResult, ProcessedFile, Variant, TranscodeOptions, TranscodeResult, EncodeHooks, EncodeContext, and PresetName.
import type { OptimizeResult, Variant } from 'pixelpress';
const variants: Variant[] = report.files.flatMap((file) => file.outputs);
function summarize(result: OptimizeResult) {
return result.totals.savedPercent ?? 0;
}
Call transcode(buffer, { format: 'webp', maxBytes }) before writing storage.
Enable cache + prune so removed sources and retired widths disappear.
Check report.failed and pruneErrors, then set a non-zero exit code.
More end-to-end examples: Recipes & command builder →