Skip to content
the poor coder

cheerio load from file

Poor Man
Published
Reading time
2 min read
On this page

Cheerio Load from File#

As a web developer, I have worked with many HTML parsing libraries and one of my favorites is Cheerio. Cheerio is a fast, flexible, and lean implementation of core jQuery designed specifically for the server. It allows you to manipulate and traverse HTML documents using the same syntax as jQuery, which makes it a great choice for web scraping, testing, and data mining.

How to Load HTML from a File using Cheerio#

One of the most common tasks when working with Cheerio is to load an HTML file and parse it. Cheerio provides a simple API for loading HTML from a file:

Text

const fs = require('fs');
const cheerio = require('cheerio');

const html = fs.readFileSync('path/to/file.html', 'utf8');
const $ = cheerio.load(html);
  • The fs.readFileSync() method reads the contents of the file synchronously and returns a string.
  • The cheerio.load() method loads the HTML string into a Cheerio object.

Once you have loaded the HTML into a Cheerio object, you can use the same syntax as jQuery to manipulate and traverse the HTML:

Text

$('h1').text('Hello Cheerio!');

This code selects all <h1> elements in the HTML document and sets their text content to Hello Cheerio!.

Other Ways to Load HTML using Cheerio#

Aside from loading HTML from a file, Cheerio provides several other ways to load HTML:

  • Load from a URL: You can use the cheerio.load() method with the request() module to load HTML from a URL:
Text

const request = require('request');
const cheerio = require('cheerio');

request('http://example.com', (error, response, html) => {
  const $ = cheerio.load(html);
});
  • Load from a String: You can use the cheerio.load() method to load HTML from a string:
Text

const cheerio = require('cheerio');

const html = '<html><body><p>Hello Cheerio!</p></body></html>';
const $ = cheerio.load(html);

These are just a few examples of how you can load HTML using Cheerio. With its simple and powerful API, Cheerio is an excellent tool for working with HTML on the server.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC