实现说明
唯一的导入来源是 node:fs、node:os、node:path(Node.js 内建),暴露出 readFileSync、writeFileSync、mkdtempSync、tmpdir、EOL。
dir、file、lines、normalized 定义在模块顶层,中间不经过函数作用域。
使用要点
- 唯一的导入
node:fs属于 Node.js 标准库。 - 直接运行文件,输出会带上标签,比如
has CRLF left:、line count:、platform EOL length:——输出的每一行都能指回产生它的那次调用。
常见问题
需要安装第三方包吗?
不需要——node:fs 是 Node.js 内建模块,无需安装。
核心语句
const lines = readFileSync(file, 'utf8').split(/\r?\n/);
const dir = mkdtempSync(join(tmpdir(), 'eol-'));
const normalized = readFileSync(file, 'utf8');
代码示例
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);