How do you read and parse a CSV file in JavaScript in the browser or Node.js? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you read and parse a CSV file in JavaScript in the browser or Node.js?

message-square
0

To read and parse a CSV file in JavaScript in the browser or Node.js, read the file text safely (File.prototype.text() / FileReader from an <input type="file"> in the browser, or fs.promises.readFile(path, "utf8") in Node.js), parse rows and columns while respecting quoted fields, embedded commas/newlines, and escaped double quotes ("") inside a try / catch block—validating inputs with typeof / instanceof checks and storing parsed rows/columns in a Map—and prefer a battle-tested parser (such as Papa Parse) for complex RFC 4180 / large-file edge cases.


1. Reading and Parsing CSV Text Safely in Browser and Node.js

Validate the CSV text input (typeof csvText === "string"), parse character-by-character so quoted commas, quoted newlines, and escaped quotes ("") are handled accurately, and build structured records using a Map inside try / catch:

// Parse CSV text into an array of row Maps (with optional header row)
function parseCsvTextToMaps(csvText, { delimiter = ",", hasHeader = true } = {}) {
  if (typeof csvText !== "string") {
    throw new TypeError("Expected csvText to be a string.");
  }
  if (typeof delimiter !== "string" || delimiter.length !== 1) {
    throw new TypeError("Expected delimiter to be a single-character string.");
  }
  if (typeof hasHeader !== "boolean") {
    throw new TypeError("Expected hasHeader to be a boolean.");
  }

  try {
    const rows = [];
    let currentRow = [];
    let currentField = "";
    let inQuotes = false;

    for (let i = 0; i < csvText.length; i += 1) {
      const ch = csvText[i];
      const nextCh = i + 1 < csvText.length ? csvText[i + 1] : "";

      if (inQuotes) {
        if (ch === '"' && nextCh === '"') {
          currentField += '"';
          i += 1; // Skip escaped quote
        } else if (ch === '"') {
          inQuotes = false;
        } else {
          currentField += ch;
        }
        continue;
      }

      if (ch === '"') {
        inQuotes = true;
      } else if (ch === delimiter) {
        currentRow.push(currentField);
        currentField = "";
      } else if (ch === "\r" && nextCh === "\n") {
        currentRow.push(currentField);
        rows.push(currentRow);
        currentRow = [];
        currentField = "";
        i += 1; // Consume LF in CRLF
      } else if (ch === "\n" || ch === "\r") {
        currentRow.push(currentField);
        rows.push(currentRow);
        currentRow = [];
        currentField = "";
      } else {
        currentField += ch;
      }
    }

    if (inQuotes) {
      throw new SyntaxError("Malformed CSV: unterminated quoted field.");
    }

    if (currentField.length > 0 || currentRow.length > 0) {
      currentRow.push(currentField);
      rows.push(currentRow);
    }

    // Filter completely empty trailing/blank lines
    const nonEmptyRows = rows.filter(
      (row) => !(row.length === 1 && row[0].trim() === "")
    );

    if (nonEmptyRows.length === 0) {
      return [];
    }

    const headers = hasHeader
      ? nonEmptyRows[0].map((h, idx) => (h.trim().length > 0 ? h.trim() : `column_${idx}`))
      : nonEmptyRows[0].map((_, idx) => `column_${idx}`);

    const dataRows = hasHeader ? nonEmptyRows.slice(1) : nonEmptyRows;

    return dataRows.map((cells) => {
      const recordMap = new Map();
      for (let colIdx = 0; colIdx < headers.length; colIdx += 1) {
        const key = headers[colIdx];
        const val = colIdx < cells.length ? cells[colIdx] : "";
        recordMap.set(key, val);
      }
      return recordMap;
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed parsing CSV text: ${message}`);
  }
}

// Example usage:
// try {
//   const sampleCsv = 'name,note,score\n"Ali, Khan","Said ""Hello""\nNew line",95\n';
//   const parsedMaps = parseCsvTextToMaps(sampleCsv);
//   console.log("First row note:", parsedMaps[0].get("note"));
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Avoid line.split(",") on real CSV data: Naive .split(",") breaks whenever a field contains commas inside quotes ("Lahore, Punjab") or multi-line quoted text.
  • Normalize CRLF (\r\n), LF (\n), and CR (\r): Cross-platform CSV exports vary in line endings.

2. Reading CSV Files in the Browser (File) vs. Node.js (fs) with a Map

Use File instanceof File + await file.text() in the browser or fs.promises.readFile(filePath, "utf8") in Node.js, and track file metadata/results in a Map inside try / catch:

// Browser: Read a user-selected File object and parse into row Maps
async function readAndParseBrowserCsv(fileObj, options = {}) {
  if (typeof File === "undefined" || !(fileObj instanceof File)) {
    throw new TypeError("Expected fileObj to be a browser File instance.");
  }

  try {
    const rawText = await fileObj.text();
    const records = parseCsvTextToMaps(rawText, options);

    return new Map([
      ["fileName", fileObj.name],
      ["fileSizeBytes", fileObj.size],
      ["rowCount", records.length],
      ["records", records]
    ]);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed reading browser CSV file "${fileObj.name}": ${message}`);
  }
}

// Node.js: Read a CSV file from disk with fs/promises and parse into row Maps
async function readAndParseNodeCsv(filePath, fsPromisesModule, options = {}) {
  if (typeof filePath !== "string" || filePath.trim().length === 0) {
    throw new TypeError("Expected filePath to be a non-empty string.");
  }
  if (!fsPromisesModule || typeof fsPromisesModule.readFile !== "function") {
    throw new TypeError("Expected fsPromisesModule with a readFile() function (e.g., node:fs/promises).");
  }

  try {
    const cleanPath = filePath.trim();
    const rawText = await fsPromisesModule.readFile(cleanPath, { encoding: "utf8" });
    const records = parseCsvTextToMaps(rawText, options);

    return new Map([
      ["filePath", cleanPath],
      ["rowCount", records.length],
      ["records", records]
    ]);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed reading Node CSV file "${filePath}": ${message}`);
  }
}

// Example usage (Node.js):
// import fs from "node:fs/promises";
// try {
//   const resultMap = await readAndParseNodeCsv("./data/users.csv", fs);
//   console.log("Rows parsed:", resultMap.get("rowCount"));
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Use Map for parsed row fields and file summaries: Avoids Object.prototype collisions when CSV column names come from external or untrusted files.
  • Stream large files in Node.js (fs.createReadStream): Reading huge multi-hundred-MB CSV files all at once with readFile can spike memory usage.

3. UTF-8 BOM, Delimiters, and Streaming Caveats

Keep these CSV reading and parsing edge cases in mind in production code:

  • Strip a leading UTF-8 BOM (\uFEFF) if present: Excel and some exporters prepend \uFEFF to the first column header, which otherwise corrupts the first key name.
  • Watch locale-dependent delimiters (; vs. ,) and type coercion: CSV fields start as strings—explicitly validate and parse numbers, booleans, or dates rather than assuming raw types.
  • Avoid FileReader.readAsBinaryString(): Use file.text() (or FileReader.readAsText(file, "utf-8")) for text CSV files.