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.

feat(dataset): add collectAllKeys option for full CSV export (#2945) (#3007)

Bhanu-Chauhan-uoa3b629da9418c
diff --git a/packages/core/src/storages/dataset.ts b/packages/core/src/storages/dataset.ts
index 27dd15731..ec2331492 100644
--- a/packages/core/src/storages/dataset.ts
+++ b/packages/core/src/storages/dataset.ts
@@ -170,6 +170,11 @@ export interface DatasetIteratorOptions
export interface DatasetExportToOptions extends DatasetExportOptions {
fromDataset?: string;
toKVS?: string;
+ /**
+ * If true, includes all unique keys from all dataset items in the CSV export.
+ * If omitted or false, only keys from the first item are used.
+ */
+ collectAllKeys?: boolean;
}
/**
@@ -349,7 +354,16 @@ export class Dataset<Data extends Dictionary = Dictionary> {
const items = await this.export(options);
if (contentType === 'text/csv') {
- const keys = Object.keys(items[0]);
+ // To handle empty dataset exports gracefully.
+ if (items.length === 0) {
+ await kvStore.setValue(key, '', { contentType });
+ return items;
+ }
+
+ const keys = options?.collectAllKeys
+ ? Array.from(new Set(items.flatMap(Object.keys)))
+ : Object.keys(items[0]);
+
const value = stringify([
keys,
...items.map((item) => {
diff --git a/test/core/storages/dataset.test.ts b/test/core/storages/dataset.test.ts
index 646969c5e..eec10d9d1 100644
--- a/test/core/storages/dataset.test.ts
+++ b/test/core/storages/dataset.test.ts
@@ -550,6 +550,28 @@ describe('dataset', () => {
const kvData = await KeyValueStore.getValue('TEST-123-123-csv');
expect(kvData).toEqual('hello,foo\nworld 1,bar 1\nworld 2,bar 2\nworld 3,bar 3\n');
});
+ it('should export all fields when collectAllKeys is true', async () => {
+ const dataset = await Dataset.open();
+ await dataset.pushData([
+ { id: 1, name: 'Alice' },
+ { id: 2, age: 30 },
+ ]);
+
+ const kvStore = await KeyValueStore.open();
+ await dataset.exportTo(
+ 'test.csv',
+ {
+ toKVS: kvStore.name,
+ collectAllKeys: true,
+ },
+ 'text/csv',
+ );
+
+ const exported = await kvStore.getValue('test.csv');
+ expect(exported).toContain('id');
+ expect(exported).toContain('name');
+ expect(exported).toContain('age');
+ });
});
});
});