How do I extract single record from a large CSV using csvtojson

124 Views Asked by At

I'm trying to read only the first record of a large CSV using csvtojson I've to use this library, as it will be used later to extract all the records, and I need consistency in data format between the 2 fetches.

My current code looks like this:

const sampleRecord = await new Promise((resolve, reject) => {
  csv({
    trim: true,
    checkType: true,
    ignoreEmpty: true,
    maxRowLength: 65535
  })
  .fromFile(filePath)
  .subscribe(resolve, reject);
});

console.log('res', sampleRecord);
return sampleRecord;

Now while the sampleRecord is getting printed alright on console, I'm getting an empty object returned by the line below. What could be the reason? Also, how do I stop processing after extracting the first record?

1

There are 1 best solutions below

1
On

If you only want the first record, then read the first 2 lines of the CSV and provide that string as an input to csvtojson.

Refer:

Stream and read the first two lines

Convert csv string to csv row

For the empty object that is being returned, probably you are not awaiting for the promise to return from where this method is being called.