write to a csv file in typescript

To write to a CSV file in TypeScript, first you need to install the 'csv-writer' package from npm:

index.ts
npm install csv-writer
23 chars
2 lines

Then, you can use the 'createObjectCsvWriter' method from the package to create a new CSV Writer object. After that, you can use the 'writeRecords' method of the CSV Writer object to write an array of objects to a CSV file.

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

// define the headers of the CSV file
const csvHeaders = [
  { id: 'name', title: 'Name' },
  { id: 'age', title: 'Age' },
  { id: 'email', title: 'Email' }
];

// define the data that will be written to the CSV file
const csvData = [
  { name: 'John', age: '30', email: 'john@example.com' },
  { name: 'Jane', age: '25', email: 'jane@example.com' },
  { name: 'Bob', age: '40', email: 'bob@example.com' }
];

// create a new CSV Writer object
const csvWriter = createObjectCsvWriter({
  path: 'output.csv',
  header: csvHeaders
});

// write the data to the CSV file
csvWriter.writeRecords(csvData)
  .then(() => {
    console.log('CSV file written successfully');
  })
  .catch((error) => {
    console.error(error);
  });
799 chars
32 lines

In the above example, we first define the headers of the CSV file in an array. Then, we define the data that we want to write to the CSV file in another array.

After that, we create a new CSV Writer object by calling the 'createObjectCsvWriter' method and passing the file path and headers as options.

Finally, we call the 'writeRecords' method of the CSV Writer object and pass the data array to write the contents to the file.

related categories

gistlibby LogSnag