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

การติดตั้ง

Cheerio เป็น server-side implementation ของ jQuery หลักที่ออกแบบมาสำหรับสภาพแวดล้อม Node.js โดยเฉพาะ คู่มือนี้ครอบคลุมวิธีการติดตั้งและตั้งค่า Cheerio ในโครงการของคุณทุกรูปแบบ

การติดตั้งผ่าน Package Manager

npm

npm install cheerio

yarn

yarn add cheerio

pnpm

pnpm add cheerio

bun

bun add cheerio

รูปแบบการ Import

ESM (ES Modules) - แนะนำ

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

Cheerio มาพร้อมกับ TypeScript definitions ในตัวแล้ว ไม่จำเป็นต้องติดตั้ง package @types เพิ่มเติม

การใช้งาน TypeScript พื้นฐาน

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

การใช้งาน Type ขั้นสูง

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

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

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

การรองรับสภาพแวดล้อม

ความต้องการของ Node.js

ข้อจำกัดของ Browser

⚠️ สำคัญ: Cheerio ไม่ได้ออกแบบมาสำหรับสภาพแวดล้อม browser เป็นไลบรารีฝั่ง server ที่:

สำหรับสภาพแวดล้อม browser ให้ใช้ jQuery หรือ DOM API สมัยใหม่แทน

วิธีการโหลดขั้นสูง

การโหลดจาก 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);

การโหลดจาก 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);

ตัวเลือกการกำหนดค่า

ตัวเลือก 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
});

ปัญหาการติดตั้งที่พบบ่อย

ความขัดแย้งของ Node.js Version

Error: Cannot find module 'cheerio' หรือคำเตือนความเข้ากันได้

วิธีแก้ไข: ตรวจสอบให้แน่ใจว่าคุณใช้ Node.js 18.17 หรือสูงกว่า:

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

Error: require() of ES Module หรือ import statements ใน CommonJS

วิธีแก้ไข: ตรวจสอบให้แน่ใจว่า package.json ของคุณมี module type ที่ถูกต้อง:

{
  "type": "module"
}

หรือใช้รูปแบบ import ที่เหมาะสมสำหรับสภาพแวดล้อมของคุณ

การกำหนดค่า TypeScript

Error: TypeScript compilation error กับ Cheerio types

วิธีแก้ไข: อัปเดต tsconfig.json ของคุณ:

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

ปัญหา Memory กับ Document ขนาดใหญ่

Error: JavaScript heap out of memory

วิธีแก้ไข: เพิ่มขีดจำกัด memory ของ Node.js:

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

หรือประมวลผล document เป็นชิ้นเล็กๆ โดยใช้วิธี streaming

ปัญหาการเข้ารหัส

Error: การเข้ารหัสตัวอักษรที่ไม่ถูกต้องใน HTML ที่แยกวิเคราะห์

วิธีแก้ไข: ใช้ loadBuffer() พร้อมตัวเลือกการเข้ารหัสที่ชัดเจน:

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

การตรวจสอบ

ตรวจสอบว่าการติดตั้งของคุณทำงานถูกต้อง:

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

ด้วยขั้นตอนการติดตั้งเหล่านี้ คุณพร้อมที่จะเริ่มแยกวิเคราะห์และจัดการ HTML ด้วย API ที่ทรงพลังคล้าย jQuery ของ Cheerio ใน Node.js applications ของคุณแล้ว