danielgindi/node-csv-reader

Error in reusing CsvReadableStream

Closed this issue · 2 comments

Hey!

Thanks for your awesome library!

I just faced a small bug:

  • Instantiate a CsvReadableStream:
const csvReader = new CsvReadableStream({
  skipEmptyLines: true,
  asObject: true,
  trim: true
});
  • Use csvReader in a function parseCSV()
  • Try to call the function again

Code

import CsvReadableStream from 'csv-reader';
import type { Readable } from 'stream';
import type { CSV, Customer } from './types';

const csvReader = new CsvReadableStream({
  skipEmptyLines: true,
  asObject: true,
  trim: true
});

export const parseCSV = (raw: Readable): Promise<Customer[]> => {
  const data: Customer[] = [];

  return new Promise((resolve, reject) => {
    raw
      .pipe(csvReader)
      .on('error', error => reject(`CSV: Error: "${error}"`))
      .on('data', (row: CSV) =>
        data.push({
          x: row.x
        })
      )
      .on('end', () => resolve(data));
  });
};

But if I move:

const csvReader = new CsvReadableStream({
  skipEmptyLines: true,
  asObject: true,
  trim: true
});

inside the parseCSV(), it will work!

Of course, this is how you are supposed to do it :-)
Streams are not reusable.

Thanks!