如何停止nodejs LineInputStream?

时间:2017-11-02 17:39:38

标签: node.js express

我正在处理csv文件,当我发现验证错误并希望脚本停止处理换行符时。

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.'});
    }
  });

});

1 个答案:

答案 0 :(得分:0)

在行处理函数中使用stream.destroy(),然后将错误处理程序附加到返回错误响应的流。

请参阅How to close a readable stream (before end)?