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(core): ensure correct column order in CSV export (#2734)

Martin Adámekb66784f89f01
diff --git a/packages/core/src/storages/dataset.ts b/packages/core/src/storages/dataset.ts
index 6f2e4d00a..fe0528a96 100644
--- a/packages/core/src/storages/dataset.ts
+++ b/packages/core/src/storages/dataset.ts
@@ -347,7 +347,13 @@ export class Dataset<Data extends Dictionary = Dictionary> {
const items = await this.export(options);
if (contentType === 'text/csv') {
- const value = stringify([Object.keys(items[0]), ...items.map((item) => Object.values(item))]);
+ const keys = Object.keys(items[0]);
+ const value = stringify([
+ keys,
+ ...items.map((item) => {
+ return keys.map((k) => item[k]);
+ }),
+ ]);
await kvStore.setValue(key, value, { contentType });
return items;
}
diff --git a/test/core/storages/dataset.test.ts b/test/core/storages/dataset.test.ts
index cdc709d47..98a0ff78e 100644
--- a/test/core/storages/dataset.test.ts
+++ b/test/core/storages/dataset.test.ts
@@ -486,10 +486,16 @@ describe('dataset', () => {
describe('exportToJSON', () => {
const dataToPush = [
{
- hello: 'world',
+ hello: 'world 1',
+ foo: 'bar 1',
+ },
+ {
+ foo: 'bar 2',
+ hello: 'world 2',
},
{
- foo: 'bar',
+ hello: 'world 3',
+ foo: 'bar 3',
},
];
@@ -518,8 +524,12 @@ describe('dataset', () => {
foo: 'bar 1',
},
{
- hello: 'world 2',
foo: 'bar 2',
+ hello: 'world 2',
+ },
+ {
+ hello: 'world 3',
+ foo: 'bar 3',
},
];
@@ -529,7 +539,7 @@ describe('dataset', () => {
await dataset.exportToCSV('HELLO-csv');
const kvData = await KeyValueStore.getValue('HELLO-csv');
- expect(kvData).toEqual('hello,foo\nworld 1,bar 1\nworld 2,bar 2\n');
+ expect(kvData).toEqual('hello,foo\nworld 1,bar 1\nworld 2,bar 2\nworld 3,bar 3\n');
});
it('Should work as a static method for the default dataset', async () => {
@@ -537,7 +547,7 @@ describe('dataset', () => {
await Dataset.exportToCSV('TEST-123-123-csv');
const kvData = await KeyValueStore.getValue('TEST-123-123-csv');
- expect(kvData).toEqual('hello,foo\nworld 1,bar 1\nworld 2,bar 2\n');
+ expect(kvData).toEqual('hello,foo\nworld 1,bar 1\nworld 2,bar 2\nworld 3,bar 3\n');
});
});
});