0

I am processing a csv file and when I found a validation error and want the script to stop processing newlines.

router.use(upload.single('csv')).route('/agency/:agencyId/properties/import').post(function (req, res) {

  var stream = LineInputStream(fs.createReadStream(req.file.path, {flags: 'r'}));
  stream.setDelimiter("\n");

  stream.on('line', function(line) {
    var row = line.split(',');
    if (row.length!=15) {
      stream.end(); // this does not stop the processing of new lines
      return res.status(400).json({error: 'File should have 15 columns.'});
    }
  });

});
Juan Pablo Fernandez
  • 2,408
  • 3
  • 18
  • 32

1 Answers1

0

Use stream.destroy() inside the line handler function and then attach an error handler to the stream that returns an error response.

Refer to How to close a readable stream (before end)?

Deadron
  • 5,135
  • 1
  • 16
  • 27