Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách đọc dữ liệu từ file CSV bằng JavaScript (Papa Parse)

Để parse CSV trong trình duyệt hoặc Node.js, thư viện phổ biến nhất là Papa Parse – mạnh, hỗ trợ streaming, web worker, tự động detect delimiter.

Cài đặt

// NPM
npm install papaparse

// CDN (trình duyệt)
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.4.1/papaparse.min.js"></script>

Ví dụ: Parse file CSV từ URL

Papa.parse("https://example.com/data.csv", {
  download: true,
  header: true,           // Dòng đầu làm key object
  dynamicTyping: true,    // Tự chuyển "123" → 123, "true" → true
  skipEmptyLines: true,
  complete: function(results) {
    console.log('Dữ liệu:', results.data);     // Mảng object
    console.log('Lỗi:', results.errors);       // Mảng lỗi parse
    console.log('Meta:', results.meta);        // delimiter, linebreak, v.v.
  },
  error: function(err, file) {
    console.error('Lỗi tải/parse:', err);
  }
});

Ví dụ: Parse chuỗi CSV (string)

const csvString = `Name,Age,City
John,25,"New York"
Jane,30,"San Francisco"`;

const results = Papa.parse(csvString, { header: true });
console.log(results.data);
// [{Name: "John", Age: 25, City: "New York"}, {Name: "Jane", Age: 30, City: "San Francisco"}]

Tính năng nổi bật

  • Streaming cho file lớn (chunk-by-chunk) – không load toàn bộ vào RAM.
  • Web Worker – parse off main thread, không block UI.
  • Xử lý quote, escape, multiline field chuẩn RFC 4180.
  • TypeScript types built-in.