score:0

In your row (or accessor) function, use the index (the second argument) to limit the number of rows:

If a row conversion function is specified, the specified function is invoked for each row, being passed an object representing the current row (d), the index (i) starting at zero for the first non-header row, and the array of column names. (emphasis mine)

For instance, in the following example, I'm limiting the number of rows to 5, even if the CSV has 10 rows (I'm using a <pre> element to simulate the CSV because I can't upload a real CSV using the Stack snippet):

var data = d3.csvParse(d3.select("#csv").text(), row);

function row(d, i) {
  if (i < 5) return d;
}

console.log("data length is " + data.length);
console.log("data is " + JSON.stringify(data));
pre {
  display: none;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<pre id="csv">foo,bar
12,23
13,22
43,66
3,4
66,55
43,48
32,11
11,11
21,23
78,17</pre>

Have in mind that if the CSV has in fact 20 million rows, as you said, you'll still have to wait until all the file is downloaded. The row function only limits the data array created when you parse the CSV: it will not magically stop the download/parsing process when you get to a certain row.


Related Query