Load a local CSV file in D3
How to load a local CSV file in D3: why opening the page from disk fails, how to use a local server or a file picker, and what parsing changes in your data.
Loading a CSV file from your own computer into a D3 visualization looks like a one-line job. In practice it often fails the first time, and the reason is usually the browser rather than D3. This guide covers the two reliable ways to get local CSV data into D3, what D3 does to your values during parsing, and how to check that the result is still accurate and usable.
Short answer: which approach fits your use
If you are developing a chart and the CSV sits next to your HTML file, run a simple local web server and load the file with d3.csv. That matches how the page will behave once it is deployed. If the people using your page need to supply their own CSV, use a file input and parse the text with d3.csvParse. The main benefit of either approach is that D3 turns rows into plain JavaScript objects keyed by column name. The decisive tradeoff is type handling: every value arrives as a string unless you convert it, and automatic conversion can damage values such as ZIP codes or IDs with leading zeros. If your data is small and fixed, embedding it directly in the script as an array or JSON can be simpler than loading a CSV at all.
Why opening the HTML file directly often fails
Since version 5, d3.csv uses the browser's fetch API and returns a Promise. When you open an HTML page by double-clicking it, the page runs from a file:// location, and browsers commonly restrict fetch requests from that context for security reasons. The usual symptom is an error in the developer console mentioning CORS, a blocked request or a failed fetch, and the chart never renders. The exact message and behavior vary by browser and version; no browser-specific test results were supplied for this article, so check your own console output rather than assuming one fix applies everywhere.
Option 1: Serve the folder with a local web server
Start a server from the folder that contains your HTML and CSV files. Either of these commands works if Python 3 or Node.js is installed:
# Python 3
python3 -m http.server 8000
# Node.js
npx http-server -p 8000
Open the local address the server prints in your terminal, then load the file with a relative path. Editors with a live-preview or live-server feature achieve the same thing.
d3.csv("data.csv").then(data => {
console.log(data.columns); // header names, in order
console.log(data[0]); // first row as an object
}).catch(error => {
console.error("Could not load data.csv:", error);
});
The path is resolved relative to the page, not to the script file. If the CSV lives in a subfolder, use a path such as data/sales.csv.
Option 2: Let the user choose a file
When the CSV is not part of your project, read it with a file input and pass the text to d3.csvParse. No server is required for the data itself, because the browser reads the file the user explicitly selected.
<input type="file" id="csv-file" accept=".csv,text/csv">
<script>
document.getElementById("csv-file").addEventListener("change", async event => {
const file = event.target.files[0];
if (!file) return;
const text = await file.text();
const data = d3.csvParse(text);
console.log(data.columns, data);
});
</script>
The file is read inside the browser in this pattern; nothing in the code above uploads it anywhere. If you add other libraries or analytics to the page, review what they do separately, because this snippet says nothing about them.
What parsing actually changes in your data
D3's CSV parser splits the text into rows and fields, uses the first row as keys, and returns an array of objects with an extra columns property. It handles quoted fields, so commas and line breaks inside double quotes stay part of the value. It does not change the characters inside each field. Everything is a string by default. Take this input:
name,zip,count
"Smith, Jo",02139,12
Parsing it with d3.csvParse produces the following. The quoted comma is preserved and the leading zero survives because nothing was converted:
[
{ name: "Smith, Jo", zip: "02139", count: "12" }
]
columns: ["name", "zip", "count"]
Passing d3.autoType as the row function converts values that look like numbers, booleans, empty values or ISO 8601 dates. That is convenient, but with the same input zip becomes the number 2139 and the leading zero is lost. For US ZIP codes, phone numbers, account IDs or any code that only looks numeric, write an explicit row function instead:
const parseDate = d3.timeParse("%Y-%m-%d");
d3.csv("data.csv", d => ({
name: d.name,
zip: d.zip, // keep as text
count: +d.count, // convert to number
date: parseDate(d.date) // null if the format does not match
})).then(data => {
console.log(data);
});
Watch for silent failures after conversion. A unary plus on an empty or non-numeric string gives 0 or NaN, and a date parser returns null when the format does not match. Checking a few rows in the console before drawing anything catches most of these problems.
Older D3 versions and callback syntax
Many tutorials still show d3.csv("data.csv", function(error, data) { ... }). That callback form belongs to D3 version 4 and earlier. In version 5 and later the second argument is treated as a row conversion function, so old examples fail or behave unexpectedly. If you copy code from an older source, rewrite it to use .then or await.
TSV and other delimiters
Tab-separated files use d3.tsv and d3.tsvParse with the same API. Files that use another separator, such as the semicolons some spreadsheet locales produce, need d3.dsv with the delimiter as the first argument. If every row comes back as a single long field, a delimiter mismatch is the likely cause.
d3.tsv("data.tsv").then(data => console.log(data));
d3.dsv(";", "data.csv").then(data => console.log(data));
Will the data stay readable and usable after export or sharing?
Most problems with local CSV files come from how the file was produced, not from D3. Check these points before you trust the output:
- Encoding: save the file as UTF-8. Files exported in other encodings can show garbled accented letters or symbols.
- Invisible characters: some exports add a byte order mark or trailing spaces. If a column key does not match what you expect, log data.columns and check for stray characters in the first header.
- Leading zeros: opening and resaving a CSV in a spreadsheet can strip leading zeros before D3 ever sees the file, so compare against the source.
- Line breaks inside quoted fields are valid CSV, but hand-edited files sometimes break the quoting and shift every later column.
- Exporting back: d3.csvFormat turns an array of objects into CSV text and quotes fields that need it, which is useful for round-trip checks.
For accessibility, remember that a chart drawn from the CSV is not readable by screen readers on its own. Where the data matters to the reader, provide an equivalent in plain form, such as an HTML table or a short text summary of the key values. That plain-text version is also the better choice when the data needs to be searched, copied or edited.
Limits of this review
No version-specific test results, browser compatibility measurements or tool documentation were supplied for this article. The behavior described reflects D3's documented API and general browser security principles. Confirm details such as error messages, file:// handling and character-encoding behavior in the browsers and D3 version you actually use.