Stop stream in nodejs

Viewed 275

I wrote a function that reads data from CSV using Stream, how can I stop the reading and the Stream after I call stream.destroy() and return the err.

For now, the function returns the err but does not stop reading the stream.

const tamplateHeaders = ['site_id', 'rsrp', 'longitude', 'latitude'];
const stream = fs.createReadStream(filePath, { encoding: 'utf8' });
stream
  .on('data', (chunk) => {
    //Split to rows
    chunk.split(/\r?\n/).map((row, index) => {
      //Delete sparowes
      row = row.replace(/\s+/g, '');
      //split to arr
      row = row.split(',');
      //Check first row headers
      if (index === 0 && checkHeader(row, tamplateHeaders)) {
        stream.destroy(errHandler(`Wrong ${row} column position`, 400));
        //I want to stop the stream
      }
      //Check Empty in row
      else if (checkRow(row)) {
        stream.destroy(
          errHandler(`There Spacing on row ${index} File Uploud Stop`, 400)
        );
        //I want to stop the stream
      } else {
        insertToDB(row);
        console.log(row);
      }
    });
  })
  .on('error', (err) => {
    //Delete file
    fs.unlink(filePath, (err) => {
      if (err) {
        throw err;
      }
    });
    next(err);
  })
  .on('end', () => {
    console.log('end');
    next();
  });
0 Answers
Related