DE EN ES FR ID JA KO PT RU TH VI ZH

Instalasi

Cheerio adalah implementasi server-side dari core jQuery yang dirancang khusus untuk lingkungan Node.js. Panduan ini mencakup semua cara untuk menginstal dan mengatur Cheerio dalam proyek Anda.

Instalasi Package Manager

npm

npm install cheerio

yarn

yarn add cheerio

pnpm

pnpm add cheerio

bun

bun add cheerio

Sintaks Import

ESM (ES Modules) - Direkomendasikan

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>');

Konfigurasi TypeScript

Cheerio dilengkapi dengan definisi TypeScript bawaan. Tidak diperlukan package @types tambahan.

Penggunaan TypeScript Dasar

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();

Penggunaan Type Lanjutan

import type { AnyNode, CheerioOptions } from 'cheerio';

const options: CheerioOptions = {
  xmlMode: true,
  decodeEntities: false
};

const $ = cheerio.load('<xml><item>data</item></xml>', options);

Dukungan Environment

Persyaratan Node.js

Keterbatasan Browser

⚠️ Penting: Cheerio tidak dirancang untuk environment browser. Ini adalah library server-side yang:

Untuk environment browser, gunakan jQuery atau API DOM modern sebagai gantinya.

Metode Loading Lanjutan

Loading dari Buffer

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 dari URL

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);

Opsi Konfigurasi

Opsi Parser

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
});

Masalah Instalasi Umum

Konflik Versi Node.js

Error: Cannot find module 'cheerio' atau peringatan kompatibilitas

Solusi: Pastikan Anda menggunakan Node.js 18.17 atau lebih tinggi:

node --version
# Should show v18.17.0 or higher

# Update Node.js if needed
npm install -g n  # For Unix systems
n latest

Masalah Module ESM/CommonJS

Error: require() of ES Module atau statement import dalam CommonJS

Solusi: Pastikan package.json Anda memiliki tipe module yang benar:

{
  "type": "module"
}

Atau gunakan sintaks import yang sesuai untuk environment Anda.

Konfigurasi TypeScript

Error: Error kompilasi TypeScript dengan tipe Cheerio

Solusi: Perbarui tsconfig.json Anda:

{
  "compilerOptions": {
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true
  }
}

Masalah Memory dengan Dokumen Besar

Error: JavaScript heap out of memory

Solusi: Tingkatkan batas memory Node.js:

node --max-old-space-size=4096 your-script.js

Atau proses dokumen dalam potongan yang lebih kecil menggunakan metode streaming.

Masalah Encoding

Error: Encoding karakter yang salah dalam HTML yang diparse

Solusi: Gunakan loadBuffer() dengan opsi encoding eksplisit:

const $ = cheerio.loadBuffer(buffer, {
  encoding: {
    defaultEncoding: 'utf8'
  }
});

Verifikasi

Verifikasi bahwa instalasi Anda berfungsi dengan benar:

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');

Dengan langkah-langkah instalasi ini, Anda siap untuk mulai parsing dan memanipulasi HTML dengan API Cheerio yang powerful dan mirip jQuery dalam aplikasi Node.js Anda.