A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/pawel-up/csv below:

pawel-up/csv: A CSV tools for the native web platform

🚀 CSV Parser: Effortless CSV Handling in TypeScript

Stop wrestling with CSVs! This lightweight, powerful TypeScript library makes parsing CSV data a breeze. Whether you're dealing with files or strings, complex data types, or custom formats, csv has you covered.

npm install @pawel-up/csv

or

import { CSVParser } from '@pawel-up/csv';

const csvString = "name,age,city\nJohn Doe,30,New York\nJane Smith,25,Los Angeles";
const parser = new CSVParser();

async function parseCSV() {
  const result = await parser.parse(csvString);
  console.log(result);
  // Output:
  // {
  //   format: [
  //     { name: 'name', type: 'string', index: 0 },
  //     { name: 'age', type: 'number', format: 'integer', index: 1 },
  //     { name: 'city', type: 'string', index: 2 }
  //   ],
  //   header: ['name', 'age', 'city'],
  //   values: [
  //     ['John Doe', 30, 'New York'],
  //     ['Jane Smith', 25, 'Los Angeles']
  //   ]
  // }
}

parseCSV();

For large CSV files, you can use the streaming functionality to process data in chunks:

import { CSVParser } from '@pawel-up/csv';

async function streamCSV() {
  // Assuming you have a file input element:
  const fileInput = document.getElementById('fileInput') as HTMLInputElement;
  const file = fileInput.files[0];

  const parser = new CSVParser();
  const stream = await parser.streamFile(file);

  const reader = stream.getReader();
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    console.log('Chunk:', value);
    // Process each chunk of data here
    // Example:
    // value.values.forEach(row => {
    //   console.log(row);
    // });
  }
}

streamCSV();

Mind that the headers structure may change witch every chunk as more data becomes available to check for data types.

import { CSVParser, type ParseResult } from '@pawel-up/csv'

const response = await fetch("./data.csv")
const textStream = response.body!.pipeThrough(new TextDecoderStream())
const parser = new CSVParser()
const stream = parser.stream(textStream)
const reader = stream.getReader()
const chunks: ParseResult[] = []
while (true) {
  const { done, value } = await reader.read()
  if (done) break
  chunks.push(value)
}

The CSVParser constructor accepts an optional CSVOptions object to customize the parsing behavior:

interface CSVOptions {
  delimiter?: string; // Default: ','
  quote?: string; // Default: '"'
  comment?: string; // Default: ''
  header?: boolean; // Default: true
  encoding?: string; // Default: 'utf8'
  maxRows?: number; // Default: Infinity
}

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4