Installation
Cheerio is a server-side implementation of core jQuery designed specifically for Node.js environments. This guide covers all the ways to install and set up Cheerio in your projects.
Package Manager Installation
npm
npm install cheerio
yarn
yarn add cheerio
pnpm
pnpm add cheerio
bun
bun add cheerio
Import Syntax
ESM (ES Modules) - Recommended
import * as cheerio from 'cheerio';
// Load HTML and create a Cheerio instance
const $ = cheerio.load('<h2 class="title">Hello world</h2>');
// Manipulate elements
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
console.log($.html());
// => <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>
CommonJS
const cheerio = require('cheerio');
const $ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
Destructured Imports
// Import specific functions
import { load, contains, merge } from 'cheerio';
const $ = load('<ul><li>Apple</li><li>Orange</li></ul>');
TypeScript Setup
Cheerio comes with built-in TypeScript definitions. No additional @types package is required.
Basic TypeScript Usage
import * as cheerio from 'cheerio';
import type { CheerioAPI, Element } from 'cheerio';
const html = '<div class="container"><p>Hello</p></div>';
const $: CheerioAPI = cheerio.load(html);
// Type-safe element selection
const elements: cheerio.Cheerio<Element> = $('.container p');
const text: string | undefined = elements.text();
Advanced Type Usage
import type { AnyNode, CheerioOptions } from 'cheerio';
const options: CheerioOptions = {
xmlMode: true,
decodeEntities: false
};
const $ = cheerio.load('<xml><item>data</item></xml>', options);
Environment Support
Node.js Requirements
- Minimum Node.js version: 18.17 or higher
- Recommended: Node.js 20+ for best performance
- Cheerio is designed exclusively for server-side use
Browser Limitations
⚠️ Important: Cheerio is not designed for browser environments. It's a server-side library that:
- Uses Node.js-specific APIs
- Doesn't include DOM inconsistency handling that jQuery provides
- Is optimized for server-side HTML parsing and manipulation
For browser environments, use jQuery or modern DOM APIs instead.
Advanced Loading Methods
Loading from Buffers
import * as cheerio from 'cheerio';
import * as fs from 'fs';
// Load from buffer with encoding detection
const buffer = fs.readFileSync('index.html');
const $ = cheerio.loadBuffer(buffer);
Loading from URLs
import * as cheerio from 'cheerio';
// Fetch and parse HTML from a URL
const $ = await cheerio.fromURL('https://example.com');
console.log($('title').text());
Streaming HTML
import * as cheerio from 'cheerio';
import * as fs from 'fs';
// Parse HTML streams
const writeStream = cheerio.stringStream({}, (err, $) => {
if (err) {
console.error('Parse error:', err);
return;
}
console.log($('h1').text());
});
fs.createReadStream('document.html', { encoding: 'utf8' })
.pipe(writeStream);
Configuration Options
Parser Options
import * as cheerio from 'cheerio';
const $ = cheerio.load(html, {
// Use XML mode for XML documents
xmlMode: false,
// Decode HTML entities
decodeEntities: true,
// Set base URI for resolving relative URLs
baseURI: 'https://example.com',
// Enable/disable scripting
scriptingEnabled: false
});
Common Installation Issues
Node.js Version Conflicts
Error: Cannot find module 'cheerio' or compatibility warnings
Solution: Ensure you're using Node.js 18.17 or higher:
node --version
# Should show v18.17.0 or higher
# Update Node.js if needed
npm install -g n # For Unix systems
n latest
ESM/CommonJS Module Issues
Error: require() of ES Module or import statements in CommonJS
Solution: Ensure your package.json has the correct module type:
{
"type": "module"
}
Or use the appropriate import syntax for your environment.
TypeScript Configuration
Error: TypeScript compilation errors with Cheerio types
Solution: Update your tsconfig.json:
{
"compilerOptions": {
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true
}
}
Memory Issues with Large Documents
Error: JavaScript heap out of memory
Solution: Increase Node.js memory limit:
node --max-old-space-size=4096 your-script.js
Or process documents in smaller chunks using streaming methods.
Encoding Problems
Error: Incorrect character encoding in parsed HTML
Solution: Use loadBuffer() with explicit encoding options:
const $ = cheerio.loadBuffer(buffer, {
encoding: {
defaultEncoding: 'utf8'
}
});
Verification
Verify your installation works correctly:
import * as cheerio from 'cheerio';
const $ = cheerio.load('<h1>Test</h1>');
console.log($('h1').text()); // Should output: "Test"
// Check version
console.log('Cheerio version:', cheerio.version || 'Version info not available');
With these installation steps, you're ready to start parsing and manipulating HTML with Cheerio's powerful, jQuery-like API in your Node.js applications.