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(utils): keep sitemap.txt lines apart when a chunk ends on a line break (#4329)

SwastikTripathid01f814904a2
diff --git a/packages/utils/src/internals/sitemap.ts b/packages/utils/src/internals/sitemap.ts
index d4c16ecd6..1379bb937 100644
--- a/packages/utils/src/internals/sitemap.ts
+++ b/packages/utils/src/internals/sitemap.ts
@@ -53,26 +53,15 @@ class SitemapTxtParser extends Transform {
}
#processBuffer(input: string, finalize: boolean): void {
- this.#buffer += input;
+ const lines = (this.#buffer + input).split('\n');
- if (finalize || this.#buffer.includes('\n')) {
- const parts = this.#buffer
- .split('\n')
- .map((part) => part.trim())
- .filter((part) => part.length > 0);
+ // The text after the last line break may be a partial line, so it waits for the next chunk.
+ this.#buffer = finalize ? '' : lines.pop()!;
- if (finalize) {
- for (const url of parts) {
- this.push({ type: 'url', loc: url } satisfies SitemapItem);
- }
-
- this.#buffer = '';
- } else if (parts.length > 0) {
- for (const url of parts.slice(0, -1)) {
- this.push({ type: 'url', loc: url } satisfies SitemapItem);
- }
-
- this.#buffer = parts.at(-1)!;
+ for (const line of lines) {
+ const url = line.trim();
+ if (url.length > 0) {
+ this.push({ type: 'url', loc: url } satisfies SitemapItem);
}
}
}
diff --git a/test/utils/sitemap.test.ts b/test/utils/sitemap.test.ts
index 0defe2247..e479860a2 100644
--- a/test/utils/sitemap.test.ts
+++ b/test/utils/sitemap.test.ts
@@ -448,6 +448,32 @@ describe('Sitemap', () => {
expect(logger.warningOnce).not.toHaveBeenCalled();
});
+ it('keeps sitemap.txt lines apart when a network chunk ends on a line break', async () => {
+ const urls = Array.from({ length: 300 }, (_, i) => `http://not-exists.com/page-${i}`);
+ const httpClient = new FetchHttpClient();
+ httpClient.sendRequest = async () =>
+ new Response(
+ new ReadableStream({
+ start(controller) {
+ for (const url of urls) {
+ controller.enqueue(new TextEncoder().encode(`${url}\n`));
+ }
+ controller.close();
+ },
+ }),
+ { headers: { 'content-type': 'text/plain' } },
+ );
+
+ const parsed: string[] = [];
+ for await (const item of parseSitemap([{ type: 'url', url: 'http://not-exists.com/sitemap.txt' }], undefined, {
+ httpClient,
+ })) {
+ parsed.push(item.loc);
+ }
+
+ expect(parsed).toEqual(urls);
+ });
+
it('handles sitemap.txt correctly', async () => {
const sitemap = await Sitemap.load('http://not-exists.com/sitemap.txt', undefined, {
httpClient: new FetchHttpClient(),