RunJS
RunJS copied to clipboard
Odd issue with Cheerio
I installed Cheerio via RunJS's NPM support and tried a super simple script:
import * as cheerio from 'cheerio';
const $ = await cheerio.fromURL('https://www.raymondcamden.com');
I got:
Uncaught TypeError: this.timeout.unref is not a function
So my assumption was that it was a Cheerio issue. I reported it here, https://github.com/cheeriojs/cheerio/issues/4310#issuecomment-2954249583, and figured out that the same code works just fine in a simple file on my file system. It only shows this issue in RunJS.
@cfjedimaster thanks for raising this. Seems like the error is originating from a dependency of cheerio called undici. I'm not currently sure why it's only occurring when running in RunJS. I will investigate further.
The reason for the error is due to the difference in how setTimeout is implemented in Node.js versus how it's implemented in the browser.
In Node, setTimeout returns an object which includes methods like unref. In the browser, setTimeout just returns a number which acts as an id.
So one solution to resolve your issue could be to import setTimeout from Node and override the built-in setTimeout, like this:
import { setTimeout } from 'node:timers';
import * as cheerio from 'cheerio';
window.setTimeout = setTimeout;
const $ = await cheerio.fromURL('https://www.raymondcamden.com');
I had no idea it differed in Node. So - not a bug then - but maybe something to document as a warning?