0

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?

Gaurav
  • 347
  • 4
  • 12

1 Answers1

0

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.

Muthukumar
  • 8,679
  • 17
  • 61
  • 86
  • Actually I'm awaiting the promise, as you can see on the first line itself. The record is getting console logged as well, but not being returned. In any case, I think if there was such an issue then the returned value would be null or undefined, but not an empty object. – Gaurav Dec 30 '22 at 09:36