Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

Fix unnecessary response reads

Ondra Urban858dd671a3e6
diff --git a/src/cheerio_crawler.js b/src/cheerio_crawler.js
index 4a0784479..298757100 100644
--- a/src/cheerio_crawler.js
+++ b/src/cheerio_crawler.js
@@ -323,6 +323,7 @@ class CheerioCrawler {
// Using the streaming API of Request to be able to
// handle the response based on headers receieved.
this.rqst(this._getRequestOptions(request))
+ .on('error', err => reject(err))
.on('response', async (res) => {
// First check what kind of response we received.
let cType;
@@ -335,18 +336,17 @@ class CheerioCrawler {
}
const { type, encoding } = cType;
- // Read the body into a string since Cheerio does not support streaming.
- let body;
- try {
- body = await this._readStreamIntoString(res, encoding);
- } catch (err) {
- // Error in reading the body.
- return reject(err);
- }
// 500 codes are handled as errors, requests will be retried.
const status = res.statusCode;
if (status >= 500) {
+ let body;
+ try {
+ body = await this._readStreamIntoString(res, encoding);
+ } catch (err) {
+ // Error in reading the body.
+ return reject(err);
+ }
// Errors are often sent as JSON, so attempt to parse them,
// despite Accept header being set to text/html.
if (type === 'application/json') {
@@ -363,21 +363,27 @@ class CheerioCrawler {
// it will not serve the resource as text/html by skipping.
if (status === 406) {
request.skip();
+ res.destroy();
return reject(new Error(`CheerioCrawler: Resource ${request.url} is not available in HTML format. Skipping resource.`));
}
// Other 200-499 responses are considered OK, but first check the content type.
if (type === 'text/html') {
- res.body = body;
- resolve(res);
+ try {
+ res.body = await this._readStreamIntoString(res, encoding);
+ resolve(res);
+ } catch (err) {
+ // Error in reading the body.
+ reject(err);
+ }
} else {
request.skip();
+ res.destroy();
reject(new Error(
`CheerioCrawler: Resource ${request.url} served Content-Type ${type} instead of text/html. Skipping resource.`,
));
}
- })
- .on('error', err => reject(err));
+ });
});
}
diff --git a/test/cheerio_crawler.js b/test/cheerio_crawler.js
index 8d1b08fe3..90b34f44d 100644
--- a/test/cheerio_crawler.js
+++ b/test/cheerio_crawler.js
@@ -302,6 +302,11 @@ describe('CheerioCrawler', () => {
let crawler;
let handlePageInvocationCount = 0;
let errorMessages = [];
+ let chunkReadCount = 0;
+ const getChunk = (chunk = 'x') => {
+ chunkReadCount++;
+ return chunk;
+ };
beforeEach(() => {
log.setLevel(log.LEVELS.OFF);
crawler = new Apify.CheerioCrawler({
@@ -319,6 +324,7 @@ describe('CheerioCrawler', () => {
log.setLevel(log.LEVELS.ERROR);
crawler = null;
handlePageInvocationCount = 0;
+ chunkReadCount = 0;
errorMessages = [];
});
@@ -328,7 +334,7 @@ describe('CheerioCrawler', () => {
crawler.rqst = () => {
const response = new Readable({
read() {
- this.push('x');
+ this.push(getChunk());
this.push(null);
},
});
@@ -350,6 +356,7 @@ describe('CheerioCrawler', () => {
expect(handlePageInvocationCount).to.be.eql(0);
expect(errorMessages).to.have.lengthOf(8);
errorMessages.forEach(msg => expect(msg).to.include('Invalid Content-Type header'));
+ expect(chunkReadCount).to.be.eql(0);
});
it('when response stream emits an error event', async () => {
@@ -362,7 +369,7 @@ describe('CheerioCrawler', () => {
this.emit('error', new Error('Error in stream.'));
return;
}
- this.push('x');
+ this.push(getChunk());
},
});
response.headers = {
@@ -418,9 +425,8 @@ describe('CheerioCrawler', () => {
it('when statusCode >= 500 and text/html is received', async () => {
crawler.rqst = () => {
const response = new Readable({
- // Just do nothing
read() {
- this.push('x');
+ this.push(getChunk());
this.push(null);
},
});
@@ -443,6 +449,7 @@ describe('CheerioCrawler', () => {
expect(handlePageInvocationCount).to.be.eql(0);
expect(errorMessages).to.have.lengthOf(8);
errorMessages.forEach(msg => expect(msg).to.include('Internal Server Error: x'));
+ expect(chunkReadCount).to.be.eql(8);
});
it('when statusCode >= 500 and application/json is received', async () => {
@@ -450,7 +457,7 @@ describe('CheerioCrawler', () => {
const response = new Readable({
// Just do nothing
read() {
- this.push(JSON.stringify({ message: 'Hello' }));
+ this.push(getChunk(JSON.stringify({ message: 'Hello' })));
this.push(null);
},
});
@@ -473,6 +480,7 @@ describe('CheerioCrawler', () => {
expect(handlePageInvocationCount).to.be.eql(0);
expect(errorMessages).to.have.lengthOf(8);
errorMessages.forEach(msg => expect(msg).to.include('500 - Hello'));
+ expect(chunkReadCount).to.be.eql(8);
});
it('when 406 is received', async () => {
@@ -480,7 +488,7 @@ describe('CheerioCrawler', () => {
crawler.rqst = () => {
const response = new Readable({
read() {
- this.push('x');
+ this.push(getChunk());
this.push(null);
},
});
@@ -503,6 +511,7 @@ describe('CheerioCrawler', () => {
expect(handlePageInvocationCount).to.be.eql(0);
expect(errorMessages).to.have.lengthOf(4);
errorMessages.forEach(msg => expect(msg).to.include('is not available in HTML format'));
+ expect(chunkReadCount).to.be.eql(0);
});
it('when status is ok, but a wrong content type is received', async () => {
@@ -510,7 +519,7 @@ describe('CheerioCrawler', () => {
crawler.rqst = () => {
const response = new Readable({
read() {
- this.push('x');
+ this.push(getChunk());
this.push(null);
},
});
@@ -533,6 +542,7 @@ describe('CheerioCrawler', () => {
expect(handlePageInvocationCount).to.be.eql(0);
expect(errorMessages).to.have.lengthOf(4);
errorMessages.forEach(msg => expect(msg).to.include('served Content-Type application/json instead of text/html'));
+ expect(chunkReadCount).to.be.eql(0);
});
});
});