node-csvtojson icon indicating copy to clipboard operation
node-csvtojson copied to clipboard

How to get a single record?

Open gaurav-mtalkz opened this issue 2 years ago • 0 comments

I need to get only the first record of a large CSV in JSON format.

The idea is to upload the file, parse the first record, get columns verified by the users (with sample data of first record), and then post approval finally process the records for insertion to a mongodb collection.

I'm using the below code to parse the first record:

    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 { filePath, sampleRecord };

Now console.log is able to print the record, whereas return gives me an empty object.

What am I missing here?

I've also tried below to stop processing after the first record, to no avail:

      const parser = csv({
        trim: true,
        checkType: true,
        ignoreEmpty: true,
        maxRowLength: 65535
      })
      .fromFile(filePath)
      .subscribe(obj => {
        parser.emit('end');
        resolve(obj);
      }, reject);

gaurav-mtalkz avatar Dec 30 '22 07:12 gaurav-mtalkz