{"id":11570,"library":"pngquant","title":"PNGQuant Stream Wrapper","description":"The `pngquant` package provides a Node.js readable/writable stream wrapper for the `pngquant` command-line utility. It allows developers to optimize PNG images by reducing their color palette directly within a Node.js stream pipeline, making it suitable for processing images from HTTP requests, file uploads, or other stream sources without requiring temporary files. Currently at version 4.2.0, its release cadence is not explicitly stated in the provided information, but it appears actively maintained given recent version bumps and project activity. Key differentiators include its efficient stream-based API, direct integration with the powerful `pngquant` CLI for high-quality optimization, and robust TypeScript type definitions for enhanced developer experience. This design simplifies image optimization workflows in server-side applications and microservices.","status":"active","version":"4.2.0","language":"javascript","source_language":"en","source_url":"git://github.com/papandreou/node-pngquant","tags":["javascript","pngquant","png","image","optimization","stream","filter","read/write","duplex","typescript"],"install":[{"cmd":"npm install pngquant","lang":"bash","label":"npm"},{"cmd":"yarn add pngquant","lang":"bash","label":"yarn"},{"cmd":"pnpm add pngquant","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary class is a default export, representing the stream transformer.","wrong":"import { PngQuant } from 'pngquant';","symbol":"PngQuant","correct":"import PngQuant from 'pngquant';"},{"note":"CommonJS import for environments that do not support ES modules natively.","symbol":"PngQuant (CommonJS)","correct":"const PngQuant = require('pngquant');"},{"note":"Import the TypeScript type definition for configuring the PngQuant constructor options. It's a type-only import.","wrong":"import { PngQuantOptions } from 'pngquant';","symbol":"PngQuantOptions","correct":"import type { PngQuantOptions } from 'pngquant';"}],"quickstart":{"code":"import PngQuant from 'pngquant';\nimport { createReadStream, createWriteStream, promises as fsPromises } from 'fs';\nimport { pipeline } from 'stream/promises';\nimport path from 'path';\n\n// Ensure a dummy input.png exists for this example to run.\n// In a real application, 'input.png' would be provided by user upload or file system.\nconst inputFilePath = path.resolve(__dirname, 'input.png');\nconst outputFilePath = path.resolve(__dirname, 'output.png');\n\nasync function createDummyPng() {\n  const dummyPngContent = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=', 'base64');\n  await fsPromises.writeFile(inputFilePath, dummyPngContent);\n  console.log(`Created dummy PNG at ${inputFilePath}`);\n}\n\nasync function optimizeImage() {\n  await createDummyPng(); // Create a dummy PNG for the example\n  try {\n    // Initialize PngQuant with specific command-line arguments for the pngquant binary.\n    // Here: reduce to 192 colors, target quality 60-80, disable dithering, read from stdin ('-').\n    const myPngQuanter = new PngQuant([192, '--quality', '60-80', '--nofs', '-']);\n    console.log(`Optimizing ${inputFilePath} to ${outputFilePath}...`);\n\n    await pipeline(\n      createReadStream(inputFilePath), // Source stream: reads the input PNG\n      myPngQuanter,                  // Transform stream: optimizes the PNG\n      createWriteStream(outputFilePath)  // Destination stream: writes the optimized PNG\n    );\n    console.log(`Optimization complete! Optimized PNG saved to ${outputFilePath}`);\n  } catch (error) {\n    console.error('Image optimization failed:', error);\n  } finally {\n    // Clean up the dummy file\n    await fsPromises.unlink(inputFilePath).catch(() => {});\n  }\n}\n\noptimizeImage();","lang":"typescript","description":"Demonstrates how to optimize a PNG file from a read stream to a write stream using custom `pngquant` command-line options within a Node.js pipeline."},"warnings":[{"fix":"Install the `pngquant` command-line utility via your system's package manager (e.g., `brew install pngquant` on macOS, `sudo apt install pngquant` on Debian/Ubuntu, or download from the official `pngquant` website).","message":"The `pngquant` binary is a required runtime dependency and must be installed separately and available in the system's PATH. This package does not bundle the native executable.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Refer to the official `pngquant` command-line documentation for valid arguments and their syntax (e.g., run `pngquant --help` in your terminal). Test options thoroughly to ensure desired behavior.","message":"Incorrectly passing options to the `PngQuant` constructor can lead to unexpected optimization results or errors from the underlying `pngquant` binary. The options array is passed directly as command-line arguments.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Use `stream/promises.pipeline` for robust error handling and proper cleanup of streams in a chain. Alternatively, attach `error` event listeners to all individual streams in the pipeline (input, `PngQuant`, output) and handle errors appropriately.","message":"Stream errors from either the input, output, or the `PngQuant` transform stream itself might not always be propagated or handled gracefully if not explicitly listened for. The `pipeline` utility from `stream/promises` is recommended for robust error handling in stream chains.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure the `pngquant` command-line utility is installed and its location is included in your system's PATH. Verify installation by running `pngquant --version` in your terminal.","cause":"The `pngquant` executable is not found in the system's PATH environment variable.","error":"spawn pngquant ENOENT"},{"fix":"Verify that the input stream provides a valid PNG image. Check the options array passed to the `PngQuant` constructor for correctness and compatibility with the `pngquant` CLI version and the input image (e.g., valid quality ranges, color counts).","cause":"The underlying `pngquant` binary encountered an error during image processing, often due to invalid input (e.g., corrupted PNG) or incompatible command-line options.","error":"Error: PngQuant exited with code 98"}],"ecosystem":"npm"}