read a csv file in typescript

To read a csv file in typescript, we can make use of the fs module from Node.js along with a third-party library like csv-parser for parsing the csv data.

Here's an example code snippet that reads a csv file named data.csv and logs its contents to the console:

index.ts
import fs from 'fs';
import csv from 'csv-parser';

const results = [];

fs.createReadStream('data.csv')
  .pipe(csv())
  .on('data', (data) => results.push(data))
  .on('end', () => {
    console.log(results);
  });
217 chars
12 lines

In the above code, fs.createReadStream() creates a readable stream for the csv file, which is then piped to the csv() function from the csv-parser library. This function parses each row of the csv data into a JavaScript object, which is pushed into an array named results. Finally, when the stream is finished, the contents of results are logged to the console.

gistlibby LogSnag