os.EOL Normalizes CRLF And LF Endings
Normalize mixed line endings by splitting on /\r?\n/ and rejoining with os.EOL, so written files use the platform-native terminator.
Code
import { readFileSync, writeFileSync, mkdtempSync } from 'node:fs';
import { tmpdir, EOL } from 'node:os';
import { join } from 'node:path';
const dir = mkdtempSync(join(tmpdir(), 'eol-'));
const file = join(dir, 'mixed.txt');
writeFileSync(file, 'alpha\r\nbeta\ngamma');
// \r?\n matches both CRLF and LF in one split; EOL joins with the
// platform-native ending
const lines = readFileSync(file, 'utf8').split(/\r?\n/);
writeFileSync(file, lines.join(EOL));
const normalized = readFileSync(file, 'utf8');
console.log('has CRLF left:', normalized.includes('\r\n'));
console.log('line count:', lines.length);
// On Windows EOL is \r\n, elsewhere \n — read it, never hardcode it
console.log('platform EOL length:', EOL.length);How it works
The only import source is node:fs, node:os, node:path, a Node.js built-in, exposing readFileSync, writeFileSync, mkdtempSync, tmpdir, EOL.
Top-level bindings dir, file, lines, normalized hold the demo state — nothing sits inside a function scope.
Caveats
node:fsis a Node.js built-in module — it ships with the runtime, so there is nothing to install.
Putting it to use
Output lines are prefixed (has CRLF left:, line count:, platform EOL length:), making each step’s effect easy to spot.
Core lines
const lines = readFileSync(file, 'utf8').split(/\r?\n/);
const dir = mkdtempSync(join(tmpdir(), 'eol-'));
const normalized = readFileSync(file, 'utf8');
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- No — `node:fs` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.