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

Cài đặt

Cheerio là một phiên bản triển khai jQuery cốt lõi phía server được thiết kế đặc biệt cho môi trường Node.js. Hướng dẫn này bao gồm tất cả các cách để cài đặt và thiết lập Cheerio trong các dự án của bạn.

Cài đặt qua Package Manager

npm

npm install cheerio

yarn

yarn add cheerio

pnpm

pnpm add cheerio

bun

bun add cheerio

Cú pháp Import

ESM (ES Modules) - Được khuyến nghị

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

Import có cấu trúc

// Import specific functions
import { load, contains, merge } from 'cheerio';

const $ = load('<ul><li>Apple</li><li>Orange</li></ul>');

Thiết lập TypeScript

Cheerio đi kèm với định nghĩa TypeScript tích hợp sẵn. Không cần package @types bổ sung.

Sử dụng TypeScript cơ bản

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

Sử dụng kiểu dữ liệu nâng cao

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

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

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

Hỗ trợ môi trường

Yêu cầu Node.js

Hạn chế trình duyệt

⚠️ Quan trọng: Cheerio không được thiết kế cho môi trường trình duyệt. Đây là thư viện phía server mà:

Đối với môi trường trình duyệt, hãy sử dụng jQuery hoặc các DOM API hiện đại thay thế.

Phương pháp tải nâng cao

Tải từ 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);

Tải từ 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);

Tùy chọn cấu hình

Tùy chọn 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
});

Các vấn đề cài đặt thường gặp

Xung đột phiên bản Node.js

Lỗi: Cannot find module 'cheerio' hoặc cảnh báo tương thích

Giải pháp: Đảm bảo bạn đang sử dụng Node.js 18.17 trở lên:

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

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

Vấn đề ESM/CommonJS Module

Lỗi: require() of ES Module hoặc câu lệnh import trong CommonJS

Giải pháp: Đảm bảo package.json của bạn có loại module đúng:

{
  "type": "module"
}

Hoặc sử dụng cú pháp import phù hợp cho môi trường của bạn.

Cấu hình TypeScript

Lỗi: Lỗi biên dịch TypeScript với các kiểu dữ liệu của Cheerio

Giải pháp: Cập nhật tsconfig.json của bạn:

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

Vấn đề bộ nhớ với tài liệu lớn

Lỗi: JavaScript heap out of memory

Giải pháp: Tăng giới hạn bộ nhớ của Node.js:

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

Hoặc xử lý tài liệu theo từng phần nhỏ hơn bằng phương pháp streaming.

Vấn đề mã hóa

Lỗi: Mã hóa ký tự không chính xác trong HTML được phân tích

Giải pháp: Sử dụng loadBuffer() với các tùy chọn mã hóa rõ ràng:

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

Xác minh

Xác minh cài đặt của bạn hoạt động chính xác:

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

Với các bước cài đặt này, bạn đã sẵn sàng bắt đầu phân tích và thao tác HTML với API mạnh mẽ giống jQuery của Cheerio trong các ứng dụng Node.js của mình.