create a csv file in typescript

To create a CSV file in TypeScript, we can use the fs module of Node.js along with the csv-writer module, which provides an easy way to write rows to a CSV file.

Here's a sample code snippet that shows how to create a CSV file in TypeScript:

index.ts
import * as fs from 'fs';
import { createObjectCsvWriter } from 'csv-writer';

// define the data to write to the CSV file
const data = [
  {
    name: 'John',
    age: 30,
    city: 'New York'
  },
  {
    name: 'Mary',
    age: 25,
    city: 'Los Angeles'
  },
  {
    name: 'Bob',
    age: 40,
    city: 'Chicago'
  }
];

// create a CSV Writer object with the desired options
const csvWriter = createObjectCsvWriter({
  path: 'output.csv',
  header: [
    { id: 'name', title: 'Name' },
    { id: 'age', title: 'Age' },
    { id: 'city', title: 'City' }
  ]
});

// write data to the CSV file
csvWriter.writeRecords(data).then(() => {
  console.log('CSV file created successfully');
});

692 chars
38 lines

In this code, we first import the fs module and the createObjectCsvWriter function from the csv-writer module. We then define the data that we want to write to the CSV file, and create a csvWriter object with the desired write options, such as the output file path and the headers for the CSV file. Finally, we call the writeRecords method of the csvWriter object to write the data to the CSV file, using a Promise to handle the asynchronous I/O operation.

gistlibby LogSnag