node.jscsvnpmnode-csv-parse

Why is CreateReadStream not firing error event?


I am attempting to do some error handling for a csv file. When changing the name of the file to something that does not exists,
Error: ENOENT: no such file or directory, open 'testdat.csv' is displayed but the on error event is not fired.

Here is the current implementation:

const csv = require('csv-parser');
const fs = require('fs');

fs.createReadStream('testdat.csv')
    .pipe(csv())
    .on('open', () => {
    })
    .on('headers', (headers) => {
        validateHeader(headers);
    })
    .on('data', (data) => {
        temp.push(data);
    })
    .on('end', () => {
        validateData(temp);
    })
    .on('error', (err) => {
        console.log(err);
    });

Solution

  • You need to attach the error event handler before piping.

    const csv = require('csv-parser');
    const fs = require('fs');
    
    var readable = fs.createReadStream('testdat.csv');
    
    readable.on('error', (err) => {
        console.log(err);
    });
    
    // pipe function returns different stream
    var writable = readable.pipe(csv())
    
    writable.on('error', (err) => {
        console.log(err);
    });