Batch Processing
NodeProcess multiple images with the same pipeline and configurable concurrency.
batch()
import { batch } from 'imgcraft'
batch(inputs: (string | Buffer)[]): BatchPipelineimport { batch } from 'imgcraft'
batch(inputs: (string | Buffer)[]): BatchPipelineCreate a batch pipeline from an array of file paths or Buffers. Supports the same chainable API as img().
Output methods
Batch pipelines have a different final step — instead of .toBuffer(), use:
.toDir(outputDir: string, options?: ToDirOptions): Promise<BatchResult[]>
.toBuffers(): Promise<Buffer[]>.toDir(outputDir: string, options?: ToDirOptions): Promise<BatchResult[]>
.toBuffers(): Promise<Buffer[]>toDir() options
| Prop | Type | Default | Description |
|---|---|---|---|
| suffix | string | '' | Append a suffix to the output filename before the extension. |
| prefix | string | '' | Prepend a prefix to the output filename. |
| overwrite | boolean | true | Overwrite existing files. |
| concurrency | number | os.cpus().length | Max images processed in parallel. |
Examples
Resize and convert a folder
import { batch } from 'imgcraft'
import { glob } from 'glob'
const files = await glob('./photos/*.jpg')
await batch(files)
.resize(1200)
.webp({ quality: 85 })
.toDir('./output', { suffix: '-optimised' })import { batch } from 'imgcraft'
import { glob } from 'glob'
const files = await glob('./photos/*.jpg')
await batch(files)
.resize(1200)
.webp({ quality: 85 })
.toDir('./output', { suffix: '-optimised' })Process with progress tracking
const results = await batch(files)
.resize(800)
.webp()
.toDir('./output', { concurrency: 4 })
console.log(`Processed ${results.length} images`)const results = await batch(files)
.resize(800)
.webp()
.toDir('./output', { concurrency: 4 })
console.log(`Processed ${results.length} images`)Collect buffers in memory
const buffers = await batch(['a.jpg', 'b.jpg', 'c.jpg'])
.resize(400)
.webp({ quality: 80 })
.toBuffers()const buffers = await batch(['a.jpg', 'b.jpg', 'c.jpg'])
.resize(400)
.webp({ quality: 80 })
.toBuffers()BatchResult
Each item in the returned array contains:
| Field | Type | Description |
|---|---|---|
| input | string | Buffer | Original input reference. |
| output | string | Output file path (toDir only). |
| size | number | Output file size in bytes. |
| timing | number | Processing time in ms. |
Concurrency
By default, imgcraft uses one worker per CPU core. Reduce concurrency for AI operations which are more memory-intensive:
await batch(files)
.removeBackground()
.png()
.toDir('./output', { concurrency: 2 })await batch(files)
.removeBackground()
.png()
.toDir('./output', { concurrency: 2 })