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

설치

Cheerio는 Node.js 환경을 위해 특별히 설계된 핵심 jQuery의 서버사이드 구현입니다. 이 가이드는 프로젝트에서 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!');

구조 분해 할당 Import

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

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

TypeScript 설정

Cheerio는 내장된 TypeScript 정의를 제공합니다. 추가적인 @types package는 필요하지 않습니다.

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

고급 타입 사용법

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

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

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

환경 지원

Node.js 요구사항

브라우저 제한사항

⚠️ 중요: Cheerio는 브라우저 환경용으로 설계되지 않았습니다. 다음과 같은 서버사이드 라이브러리입니다:

브라우저 환경에서는 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());

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

설정 옵션

파서 옵션

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 버전 충돌

오류: 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 문제

오류: require() of ES Module 또는 CommonJS에서 import 구문 오류

해결방법: package.json에 올바른 module 타입이 설정되어 있는지 확인하세요:

{
  "type": "module"
}

또는 해당 환경에 적절한 import 문법을 사용하세요.

TypeScript 설정

오류: Cheerio 타입과 관련된 TypeScript 컴파일 오류

해결방법: tsconfig.json을 업데이트하세요:

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

대용량 문서 메모리 문제

오류: JavaScript heap out of memory

해결방법: Node.js 메모리 제한을 증가시키세요:

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

또는 스트리밍 방법을 사용하여 문서를 더 작은 청크로 처리하세요.

인코딩 문제

오류: 파싱된 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');

이러한 설치 단계를 통해 Node.js 애플리케이션에서 Cheerio의 강력한 jQuery 스타일 API로 HTML을 파싱하고 조작할 준비가 완료되었습니다.