| name | line-ending-parsing |
| description | Line ending handling across platforms — CRLF vs LF detection, normalization, and git config |
| lastReviewed | 2026-04-30T00:00:00.000Z |
Line Ending Parsing
Category: Cross-Platform
Time Saved: 30 minutes debugging string comparisons
Battle-tested: Yes — breaks pattern matching silently
The Problem
You split a text file into lines and process each one. It works on macOS/Linux. On Windows, your regex patterns fail to match, or string comparisons return false even though the content looks identical.
Why It Happens
Windows uses \r\n (CRLF) for line endings. Unix uses \n (LF).
"line1\r\nline2\r\nline3"
["line1\r", "line2\r", "line3"]
"line1\r" === "line1"
/^line1$/.test("line1\r")
The Rule
Always use /\r?\n/ regex for splitting text files into lines.
const lines = content.split('\n');
const lines = content.split(/\r?\n/);
Implementation Pattern
const fs = require('fs');
function parseTextFile(filepath) {
const content = fs.readFileSync(filepath, 'utf8');
const lines = content.split(/\r?\n/);
return normalizeLines(content);
}
function normalizeLines(text) {
return text.split(/\r?\n/);
}
When This Matters
| Use Case | Impact of \r |
|---|
| String equality | "word\r" !== "word" |
| Regex matching | /^word$/ fails |
| Hash/checksum | Different hash values |
| JSON parsing | Usually OK (JSON.parse handles it) |
| CSV parsing | Column values have trailing \r |
| Config parsing | Key/value lookups fail |
Common Symptoms
- "Pattern doesn't match on Windows"
- "String comparison fails but they look the same"
- "Works on Mac, breaks on Windows"
console.log shows correct content but code doesn't match
Debugging Hidden Characters
function showHidden(str) {
return str
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n');
}
console.log(showHidden(line));
Related Scenarios
Trimming Doesn't Always Help
" line1\r ".trim()
line.replace(/\r$/, '').trim()
Reading Streams
const rl = readline.createInterface({ input: stream });
rl.on('line', (line) => {
});
Writing Cross-Platform
const os = require('os');
const output = lines.join(os.EOL);
const output = lines.join('\n');
Verification Checklist
Related Skills
cloud-storage-paths — Cross-platform file access
terminal-backtick-hazard — Cross-platform command execution