Skip to content

Commit

Permalink
Fix delimiter detection and fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
jdesboeufs committed Nov 4, 2024
1 parent ff85728 commit b16c218
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
10 changes: 10 additions & 0 deletions lib/csv.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ export async function previewCsvFromStream(inputStream, options = {}) {
...parserOptions,
preview: options.previewCount || 10,
complete({meta, data, errors}) {
errors = filterErrors(errors)

const response = {
format: 'csv',
formatOptions: {
Expand Down Expand Up @@ -156,6 +158,8 @@ export function validateCsvFromStream(inputStream, options = {}) {
chunkSize: 1024 * 1024,

chunk({data, errors}, parser) {
errors = filterErrors(errors)

if (errors.length > 0) {
emitter.emit('error', new Error('Error in CSV file: ' + errors[0].code))
emitter.removeAllListeners()
Expand Down Expand Up @@ -210,3 +214,9 @@ export function createCsvReadStream(options = {}) {
Papa.parse(Papa.NODE_STREAM_INPUT, parserOptions)
)
}

/* Helpers */

function filterErrors(errors) {
return errors.filter(error => error.code !== 'UndetectableDelimiter')
}
6 changes: 3 additions & 3 deletions test/csv.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,15 @@ test('parsing invalid CSV', async t => {
})
})

test('validate CSV file / single column / no delimiter defined', t => {
test('validate CSV file / single column', t => {
const path = new URL('fixtures/single-column.csv', import.meta.url)
const inputStream = createReadStream(path)

return new Promise(resolve => {
const emitter = validateCsvFromStream(inputStream)

emitter.once('error', error => {
t.is(error.message, 'Error in CSV file: UndetectableDelimiter')
emitter.once('complete', result => {
t.true(result.isValid)
resolve()
})
})
Expand Down

0 comments on commit b16c218

Please sign in to comment.