Sharp for JavaScript (Node.js): Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: What is Sharp and why is it needed?

\n\n

Sharp is a high-performance image processing library written in C++ that provides a convenient API for Node.js. It allows you to convert images in JPEG, PNG, WebP, AVIF, TIFF, and GIF formats to other formats, resize them, crop, rotate, add effects, and much more.

\n\n

The main advantage of Sharp is speed. The library uses native libvips libraries, making it several times faster than alternatives (such as Jimp or gm). It is ideal for:

\n
    \n
  • Web servers and APIs — dynamic processing of avatars, previews, image optimization before upload.
  • \n
  • Batch processing — converting thousands of images to the required format and size.
  • \n
  • Creating thumbnails and galleries — fast thumbnail generation.
  • \n
  • Optimizing image weight — compression without quality loss (or with controlled loss).
  • \n
\n\n

Sharp works with buffers, streams, and files, making it flexible for integration into any Node.js application.

\n\n

Installation

\n\n

Sharp installation is done via npm. The library requires Node.js version 12.13.0 or higher (14+ recommended).

\n\n
npm install sharp
\n\n

If you use yarn:

\n\n
yarn add sharp
\n\n

Important: Sharp compiles native modules during installation. If you encounter errors, make sure build-essential (on Linux) or Xcode Command Line Tools (on macOS) are installed. For Windows, Visual Studio Build Tools are usually sufficient.

\n\n

After installation, import the library into your project:

\n\n
const sharp = require('sharp');
\n\n

Quick Start

\n\n

Let's write a simple script that loads an image, reduces it to a width of 300 pixels (maintaining proportions), and saves it in WebP format.

\n\n
const sharp = require('sharp');\nconst path = require('path');\n\nasync function quickStart() {\n    try {\n        await sharp('input.jpg')\n            .resize(300) // Width 300px, height will adjust automatically\n            .webp({ quality: 80 }) // Convert to WebP with 80% quality\n            .toFile('output.webp');\n        \n        console.log('Image successfully processed!');\n    } catch (error) {\n        console.error('Error:', error);\n    }\n}\n\nquickStart();
\n\n

This example demonstrates method chaining, which is the foundation of working with Sharp. Each method returns a new Sharp instance, allowing you to apply transformations sequentially.

\n\n

Main Methods and Functions

\n\n

Below are 10 key Sharp methods with detailed descriptions, parameters, and code examples.

\n\n

1. resize() — Resizing an image

\n

What it does: Changes the width and/or height of an image. Can crop or fit the image into specified boundaries.

\n

Parameters:

\n
    \n
  • width (number, optional) — new width in pixels.
  • \n
  • height (number, optional) — new height in pixels.
  • \n
  • options (object, optional):\n
      \n
    • fit (string) — fitting mode: 'cover' (fill, cropping excess), 'contain' (fit entirely), 'fill' (stretch), 'inside' (shrink to fit), 'outside' (enlarge to exceed boundaries). Default is 'cover'.
    • \n
    • position (string) — position for cropping: 'center', 'top', 'left', 'right', 'bottom', etc.
    • \n
    • withoutEnlargement (boolean) — prevent image enlargement.
    • \n
    \n
  • \n
\n

Example:

\n
// Resize to 200x200, cropping from the center\nawait sharp                    

Recommendations