Files and data

Count text lines with an explicit trailing-newline rule

Define whether a final newline terminates the last record or creates an additional empty record. For a common text-line convention, an empty file has zero lines and a trailing terminator does not add another record.

Worked example

Node.js example · save as example.mjs and run node example.mjs

function lineCount(text) {
  if (text === "") return 0;
  const normalized = text.replace(/\r\n|\r/g, "\n");
  const parts = normalized.split("\n");
  return parts.length - (normalized.endsWith("\n") ? 1 : 0);
}
console.log(lineCount(""), lineCount("one\n"), lineCount("one\n\n"));

How it works

Normalizing line endings lets one counting rule handle CRLF, CR, and LF in this small example. A final terminator closes a line, while an additional terminator represents an actual empty line. The explicit empty-file branch avoids reporting one line for no content.

Limits and mistakes

This counts physical text lines, not CSV records or JSON objects. Quoted fields can contain newlines. The implementation also allocates normalized text and split parts, so use streaming counting for large files.

Check the result

Expect 0 1 2. Include a final line without a terminator and mixed line endings before comparing the result with another tool that may use a different counting convention.

Sources

Reference documentation for the behavior used in this guide: