How to read a CSV file in JavaScript

You can read a CSV file in JavaScript with the FileReader API for client-side operations or Node.js modules like fs for server-side processing. This guide walks you through the implementation details for both environments.

Understanding the FileReader API

The FileReader API is designed for reading file contents from the user's computer. It is asynchronous and works with callback functions to handle the file data once it is read.

Reading a CSV file on the client-side

document.getElementById('input-file').addEventListener('change', event => { const file = event.target.files[0]; const reader = new FileReader(); reader.onload = function(e) { const text = e.target.result; processCSV(text); }; reader.readAsText(file); }); function processCSV(text) { // Split the text into an array of lines const lines = text.split('\\n'); lines.forEach(line => { const columns = line.split(','); // Handle the columns array }); }

Node.js 'fs' and 'readline' modules

For server-side operations, Node.js provides the fs module to read files and the readline module to handle them line by line.

Reading a CSV file on the server-side

const fs = require('fs'); const readline = require('readline'); const stream = fs.createReadStream('path/to/your/file.csv'); const reader = readline.createInterface({ input: stream, crlfDelay: Infinity }); reader.on('line', (line) => { const columns = line.split(','); // Handle the columns array }); reader.on('close', () => { // Handle the end of the file });

Parsing CSV with a library

Although JavaScript does not have a built-in CSV parser, you can use libraries like PapaParse for more advanced features like auto-detection of delimiters.

Using PapaParse to read a CSV file

Papa.parse(file, { complete: function(results) { console.log('Parsed rows:', results.data); } });

Remember to include the PapaParse library in your HTML or install it via npm for Node.js environments.

Handling CSV with headers

If your CSV has headers, you'll want to map those headers to the values in each row.

Mapping headers to values

function csvToArray(str, delimiter = ",") { const headers = str.slice(0, str.indexOf("\\n")).split(delimiter); const rows = str.slice(str.indexOf("\\n") + 1).split("\\n"); const arr = rows.map(function(row) { const values = row.split(delimiter); const el = headers.reduce(function(object, header, index) { object[header] = values[index]; return object; }, {}); return el; }); return arr; }

This function converts a CSV string into an array of objects, with each object representing a row and the headers as keys.

Invite only

We're building the next generation of data visualization.