Read from nth row in csv typescript

I am trying to read a csv file from 4th row, in my csv file first 3 rows contains some meta data in column1. But the actual number of columns in csv is 6.

eg:

metadata1
metadata2
metadata3
head01,head02,head03,head04,head05,head06
data11,data12,data13,data14,data15,data16
data21,data22,data23,data24,data25,data26

Code I am trying is:

fs.createReadStream('/path/file.csv').pipe(
        parse({ from_line: 4, fromLine: 4 }, function(data, err) {
        console.log(data);
    })
);

I am getting data as undefined. Also If I am removing the args of parse, I am getting error Error: Invalid Record Length: expect 1, got 6 on line 4. Please guide!

The error message “Error: Invalid Record Length: expect 1, got 6 on line 4” indicates that the parse function is expecting a single value per line, but it’s encountering 6 values on line 4. This is likely due to the fact that you’re skipping the first 3 rows, which contain metadata, and the actual data starts on line 4.

Here’s a corrected version of your code that should read the CSV file from the 4th row and handle the 6 columns correctly:

JavaScript

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

fs.createReadStream('/path/file.csv').pipe(
    parse({ from_line: 4, columns: true }, function (data, err) {
        if (err) {
            console.error('Error parsing CSV:', err);
            return;
        }

        console.log(data);
    })
);

Explanation:

  • from_line: 4: This option tells the parse function to start reading from the 4th row.
  • columns: true: This option tells the parse function to create an object for each row, using the column names as keys and the corresponding values as values. This will handle the 6 columns correctly.

With these changes, the data variable will contain an array of objects, each representing a row in the CSV file, starting from the 4th row. You can access the data using the column names:

JavaScript

console.log(data[0].head01); // Output: data11