High performance Node.js image processing
Sharp is a high-performance Node.js module designed for fast image processing, capable of resizing, cropping, and transforming JPEG, PNG, WebP, GIF, AVIF, and TIFF images. The current stable version is 0.34.5, and the library is actively maintained with regular updates and new features, often preceded by release candidates.
Common errors
-
Error: Cannot find module 'sharp'
cause The 'sharp' package was not installed successfully or is missing from `node_modules`.fixRun `npm install sharp` or `yarn add sharp` to ensure the package and its native dependencies are correctly installed. -
Error: The 'sharp' module is incompatible with the current Node.js version.
cause You are using a version of Node.js that is not supported by your installed 'sharp' version, often due to a major sharp version upgrade.fixCheck the `engines` field in sharp's `package.json` or consult the documentation for compatible Node.js versions. Upgrade Node.js accordingly (e.g., to 20.9.0+ for sharp >= 0.35.0). -
Error: Input file is not a valid image
cause The input file provided to `sharp()` is either corrupted, not a supported image format, or its path is incorrect.fixVerify that the input file exists, is readable, and is a valid image in a format supported by sharp (JPEG, PNG, WebP, etc.). -
RangeError: Allocation failed - JavaScript heap out of memory
cause Processing very large images or performing complex operations on multiple images simultaneously can exhaust Node.js's memory limit.fixFor very large images, consider streaming input/output or increasing Node.js's memory limit using `node --max-old-space-size=4096 script.js` (adjust `4096` as needed). -
Error: EACCES: permission denied, open 'output.webp'
cause The Node.js process does not have the necessary write permissions for the specified output directory or file.fixEnsure that the directory where you are trying to save the output file has write permissions for the user running the Node.js process. You might need to change directory permissions or choose a different output path.
Warnings
- breaking Sharp v0.35.0 and later require Node.js 20.9.0 or higher. Node.js 18 support is dropped.
- breaking The automatic `install` script in `package.json` for compiling from source has been removed.
- breaking AVIF output quality metrics have changed from `ssim` to `iq` (SSIMULACRA2-based) in v0.35.0.
- breaking The `failOnError` constructor property has been removed.
- breaking The `paletteBitDepth` property is no longer included in the `metadata` response.
Install
-
npm install sharp -
yarn add sharp -
pnpm add sharp
Imports
- sharp
const sharp = require('sharp')import sharp from 'sharp'
Quickstart
import sharp from 'sharp';
import { createWriteStream, readFileSync } from 'fs';
async function processImage() {
const inputPath = 'input.jpg'; // Replace with your input image path
const outputPath = 'output.webp';
// Create a dummy input image if it doesn't exist for demonstration
try {
readFileSync(inputPath);
} catch (error) {
const placeholderImage = Buffer.from('<svg width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="#f0f0f0" /><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="20" fill="#333">Hello</text></svg>');
await sharp(placeholderImage)
.toFile(inputPath);
console.log(`Created dummy input.jpg at ${inputPath}`);
}
try {
await sharp(inputPath)
.resize(300, 200, { fit: 'cover' })
.webp({ quality: 80 })
.toFile(outputPath);
console.log(`Image processed and saved to ${outputPath}`);
} catch (error) {
console.error(`Error processing image: ${error}`);
}
}
processImage();