How to remove image backgrounds in Node.js
bgcut exposes an object-based Node.js API. Open one remover, reuse it for the work you have, and close it when the job is finished.
Published
Install and open bgcut
The Node.js API runs background removal on the machine where your process is running. It is not a client for a hosted bgcut API.
Create one remover and keep it alive while you process related images. Reusing the instance avoids rebuilding the native runtime for every call.
bun add bgcut
Remove one background
Call removeBackground with a file path, Uint8Array, or ArrayBuffer. The result contains the encoded data plus width, height, and output format.
PNG is the natural default when you need transparency. WebP can also preserve transparency. JPEG has no alpha channel, so bgcut composites the result on white when you request JPG output.
import { writeFile } from "node:fs/promises";
import { bgcut } from "bgcut";
const remover = await bgcut();
try {
const result = await remover.removeBackground("photo.jpg", {
format: "webp",
});
await writeFile("photo.webp", result.data);
} finally {
await remover.close();
}
Process many images with one runtime
Use removeMany for files, directories, iterables, or async iterables. Processing is sequential and the instance stays warm between items.
Each yielded item reports success or failure for that source. A bad image does not have to discard the results that came before it or stop later inputs from running.
import { bgcut } from "bgcut";
const remover = await bgcut();
try {
for await (const item of remover.removeMany("photos")) {
if (!item.ok) {
console.error(item.source.input, item.error);
continue;
}
console.log(item.result);
}
} finally {
await remover.close();
}
Choose an engine only when you need to
The default engine is auto. It tries the native WebGPU runtime first and can use CPU if runtime creation fails. Use gpu when the job must require WebGPU. Use cpu when you need to force the CPU path.
Public failures use BgcutError with documented codes for model, engine, input, inference, output, and closed-state errors. Handle those codes at the boundary where your application can decide whether to retry, reject the input, or stop the job.
Do not silently turn an explicit gpu request into CPU work. An explicit engine choice is a constraint from the caller.