To compare website screenshots with Pixelmatch in Node.js, decode both PNG files into pixel buffers, make sure they have identical dimensions, pass their pixel data to pixelmatch, and check the returned mismatch count against a tolerance you choose. If you want to inspect changes, write the output buffer as a diff image. Pixelmatch’s documented Node.js example uses pngjs for PNG input and output. Pixelmatch’s README describes the result as the number of mismatched pixels.
Install Pixelmatch and pngjs
In your Node.js project, install the comparison library and the PNG reader/writer:
npm install pixelmatch pngjs
Save the following as compare.js. It uses ES module imports; if your project uses CommonJS, see the note below.
Compare two PNG screenshots and save a diff
import fs from 'node:fs';
import pixelmatch from 'pixelmatch';
import { PNG } from 'pngjs';
const baseline = PNG.sync.read(fs.readFileSync('baseline.png'));
const actual = PNG.sync.read(fs.readFileSync('actual.png'));
if (baseline.width !== actual.width || baseline.height !== actual.height) {
throw new Error(
`Screenshots must have equal dimensions: baseline is ${baseline.width}x${baseline.height}, actual is ${actual.width}x${actual.height}`
);
}
const diff = new PNG({ width: baseline.width, height: baseline.height });
const mismatchedPixels = pixelmatch(
baseline.data,
actual.data,
diff.data,
baseline.width,
baseline.height,
{ threshold: 0.1 }
);
fs.writeFileSync('diff.png', PNG.sync.write(diff));
console.log(`Mismatched pixels: ${mismatchedPixels}`);
const allowedMismatches = 100;
if (mismatchedPixels > allowedMismatches) {
console.error(`Visual comparison failed: more than ${allowedMismatches} pixels differ`);
process.exitCode = 1;
}
Run it with node compare.js. The example expects baseline.png and actual.png in the current directory, writes diff.png, prints the count, and exits unsuccessfully when the count exceeds the example tolerance. Set allowedMismatches to a value that suits your own test; 100 is an illustrative choice, not a Pixelmatch recommendation.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
For the ES module syntax, set "type": "module" in your project’s package.json, or use a .mjs filename. In a CommonJS project, load Pixelmatch with dynamic import because it is an ES module:
const pixelmatch = (await import('pixelmatch')).default;
const { PNG } = require('pngjs');
Use those declarations in place of the corresponding imports and run the script in an environment that supports top-level await, or put the code inside an async function.
What Pixelmatch compares—and what it returns
Pixelmatch compares raw image pixel data rather than opening screenshot filenames itself. In the example, pngjs decodes each PNG, and baseline.data and actual.data provide the pixel buffers. Both source images must have the same width and height. When you request a diff image, its buffer must use those same dimensions too.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
The function returns an integer: the number of pixels it classifies as mismatched under the selected options. That number is not automatically a test verdict. Decide what your project will tolerate, then fail the test when the returned count crosses that limit. Pixelmatch also allows null as the output argument when you need only the count and do not need a diff image.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Choose sensitivity and diff appearance
Set the comparison threshold
The threshold option ranges from 0 to 1; smaller values make the comparison more sensitive. The documented default is 0.1. Choose deliberately: changing sensitivity changes which pixel differences contribute to the mismatch count, so a tolerance should be calibrated for your test rather than copied as a universal pass rule.
Decide how to handle anti-aliased pixels
includeAA defaults to false, so anti-aliased pixels are detected and ignored. Set includeAA: true if you want those pixels counted as differences. This can make comparisons stricter around rendered edges, but it may also make small rendering variations more visible to the test.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Customize the diff image
Pixelmatch exposes options for the diff’s presentation: alpha adjusts the blending of unchanged pixels; aaColor, diffColor, and diffColorAlt set colors for anti-aliased and differing pixels; and diffMask renders the diff over transparency instead of the original image. These affect how the output is shown, not your project’s decision about how many mismatches to permit.
Count all mismatches or focus on a region
The current Pixelmatch README documents windowSize. Its default is Infinity, which reports mismatches across the full image. A finite window size instead reports the maximum mismatch count in any sliding square of that size. This can help identify concentrated changes rather than treating scattered differences over the whole screenshot as equivalent. Check the README for the release you have installed before relying on this option; it is not established here for every older release.
Keep screenshot comparisons meaningful
Pixelmatch reports pixel differences; it does not decide whether a page was captured under comparable conditions. For a useful baseline comparison, keep the capture setup consistent: viewport dimensions, device scale, browser and rendering environment, page state, and timing can all affect a screenshot. This is testing practice, not a guarantee that two captures will be identical. If a diff is noisy, inspect the images and the capture conditions before simply raising the allowed mismatch count.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Quick manual comparison from the command line
For a one-off PNG comparison, Pixelmatch also provides a command-line interface:
pixelmatch image1.png image2.png output.png 0.1
Use the library in a Node.js test when you need the mismatch count, a project-specific pass/fail rule, or integration with a capture pipeline. The CLI is a simpler route for quickly generating an image diff.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Troubleshooting
- Dimension mismatch: Pixelmatch requires both input images to have equal dimensions, and a requested output image must match them. Capture both screenshots at the same size, or intentionally resize/crop them before comparison.
- Cannot decode the input: The example uses
PNG.sync.read, so the files must be readable PNG images. Confirm the paths and file contents; do not pass a JPEG or WebP file to the PNG decoder. - Import or module syntax error: The sample uses ES modules. Mark the package as
"type": "module"or use.mjs; for CommonJS, dynamically import Pixelmatch as shown above. - The test fails on tiny rendering changes: Review the
threshold, anti-aliasing behavior, and allowed mismatch count. Adjust only after deciding which visual differences your test should ignore. - The count passes but the page looks wrong: A numeric tolerance can hide a meaningful localized change. Save and inspect
diff.png; consider whether a finitewindowSizeis appropriate for localized mismatch checks in the installed version. - No diff image is needed: Pass
nullas Pixelmatch’s output argument and omit the PNG encoding/write step; the function still returns the mismatch count.
Or skip the browser setup
If you still need to capture the screenshots being compared, ScreenshotNeo is a website screenshot API and MCP server for developers. One GET request can return a PNG, JPEG, WebP, or PDF. After capturing, you can compare PNG files with the Pixelmatch workflow above. See the ScreenshotNeo API documentation.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo can accept cookie or consent banners like a visitor and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents using Claude, Cursor, or another MCP client. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.
Sign up for ScreenshotNeo’s free plan to try up to 1,000 screenshots a month without a card.
Frequently Asked Questions
Does Pixelmatch compare JPEG or WebP files directly?
The workflow here uses pngjs’s PNG decoder, so convert other formats to PNG or use a decoder that produces the pixel data Pixelmatch accepts.
Is Pixelmatch’s default threshold a pass/fail tolerance?
No. The default comparison threshold is 0.1; the allowed mismatch count in a test is a separate rule you choose.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsQuick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




