如何用Node.js的fs模块读取及输出带换行符的TXT文件?
Hey there! Let's walk through exactly how to read and write TXT files with line breaks in Node.js, plus break down the three test scenarios you mentioned.
一、读取带换行符的 TXT 文件
Reading files with line breaks is straightforward with Node's built-in fs module. The key is handling different line break styles (Unix's \n, Windows's \r\n) and ensuring you're using the right encoding.
1. 异步读取(推荐用于非阻塞场景)
Use fs.readFile() with the utf8 encoding to get the file content as a string, then split it into lines using a regex that supports both line break types:
const fs = require('fs'); fs.readFile('your-file.txt', 'utf8', (err, fileContent) => { if (err) { console.error('读取文件出错:', err); return; } // 分割所有类型的换行符 const lines = fileContent.split(/\r?\n/); console.log('文件内容按行分割:', lines); });
2. 同步读取(适合脚本或简单场景)
If you prefer a synchronous approach, use fs.readFileSync()—the logic is almost identical:
const fs = require('fs'); try { const fileContent = fs.readFileSync('your-file.txt', 'utf8'); const lines = fileContent.split(/\r?\n/); console.log('文件内容按行分割:', lines); } catch (err) { console.error('读取文件出错:', err); }
二、写入带换行符的 TXT 文件 & 三次测试分析
Writing line breaks just requires including \n (or \r\n for Windows) in your content string. Let's break down your three tests:
测试1:UTF-8 编码
- 输入内容:
第一行测试文本 第二行测试文本 第三行测试文本 - 写入代码:
const fs = require('fs'); const content = '第一行测试文本\n第二行测试文本\n第三行测试文本'; fs.writeFile('output-utf8.txt', content, 'utf8', (err) => { if (err) throw err; console.log('UTF-8 编码文件写入完成'); }); - 实际输出:文件中每行结尾为 Unix 风格换行符
\n,内容与输入完全一致 - 预期输出:保留原始换行结构
- 分析:UTF-8 编码完全支持
\n换行符,写入和读取时都能正确识别,完全符合预期。
测试2:Node.js 默认 fs 编码
Node.js 当前稳定版本(v14+)默认使用 utf8 编码 for fs operations when no encoding is specified.
- 输入内容:
Hello Node.js Line Break Test 1 Line Break Test 2 - 写入代码:
const fs = require('fs'); const content = 'Hello Node.js\nLine Break Test 1\nLine Break Test 2'; fs.writeFile('output-default.txt', content, (err) => { if (err) throw err; console.log('默认编码文件写入完成'); }); - 实际输出:内容与输入一致,换行符为
\n - 预期输出:保留换行结构
- 分析:Since the default encoding is
utf8, this behaves exactly like Test 1. The line breaks are preserved perfectly.
测试3:Node.js 默认 fs 编码(Windows 风格换行输入)
This test focuses on Windows-style \r\n line breaks:
- 输入内容:
Windows 测试行 1\r\n Windows 测试行 2\r\n Windows 测试行 3 - 写入代码:
const fs = require('fs'); const content = 'Windows 测试行 1\r\nWindows 测试行 2\r\nWindows 测试行 3'; fs.writeFile('output-windows.txt', content, (err) => { if (err) throw err; console.log('默认编码下Windows换行写入完成'); }); - 实际输出:文件中保留
\r\n换行符,Windows 记事本和现代编辑器都能正确显示换行 - 预期输出:正确保留 Windows 风格换行
- 分析:The default
utf8encoding doesn't modify the line break characters—they're written exactly as provided. Both Windows and Unix-based editors can handle\r\nthese days, so this works as expected.
额外小贴士
- To automatically use the system's default line break style, use
os.EOL:const os = require('os'); const content = `Line 1${os.EOL}Line 2${os.EOL}Line 3`; - If you read a file without specifying an encoding, you'll get a Buffer—convert it to a string first to handle line breaks:
fs.readFile('file.txt', (err, bufferData) => { if (err) throw err; const textContent = bufferData.toString('utf8'); const lines = textContent.split(/\r?\n/); });
内容的提问来源于stack exchange,提问作者ang

