read csv from a file and convert it to json in typescript

To read CSV from a file and convert it into a JSON object in Typescript, we need to use the 'csv-parser' and 'fs' modules from node.js.

Here's the sample code:

index.ts
import * as csvParser from 'csv-parser';
import * as fs from 'fs';

// function to read CSV file and convert it to JSON
function csvToJson(filePath: string): Promise<any[]> {
  return new Promise((resolve, reject) => {
    const jsonArray: any[] = [];
    fs.createReadStream(filePath)
      .pipe(csvParser())
      .on('data', (data) => jsonArray.push(data))
      .on('end', () => resolve(jsonArray))
      .on('error', (error) => reject(error));
  });
}

// example usage
const filePath = 'path/to/csv/file.csv';
csvToJson(filePath)
  .then((data) => console.log(data))
  .catch((error) => console.error(error));
617 chars
21 lines

The above code reads the CSV file from the given file path using 'fs' module and pipes it to the 'csv-parser' module. The 'csv-parser' module parses the CSV file and emits a 'data' event for each row in the CSV file. We push each row to an array and finally resolve the promise with the array of JSON objects.

We can use this function to read any CSV file, and convert it into a JSON object.

gistlibby LogSnag