Node.js实现文本文件行反转遇问题,寻求解决方案
行反转文本文件问题
原文件内容(help.txt)
Hi my name is mitchell
This is my practice midterm
cheese pizza sucks
help me please
期望输出
help me please
cheese pizza sucks
this is my practice midterm
Hi name is mitchell
实际输出
esaelp em pleh
skcus azzip eseehc
mretdim ecitcarp ym si sihT
llehctim si eman ym iH
我的代码
var fs = require('fs'); fs.readFile('help.txt', function(err, data) { if(err) throw err; var array = data.toString().split("\n"); for(i in array) { console.log(array[i]); } const reversed = array.reverse(); console.log('reversed:', reversed); fs.writeFile('Output.txt', data.reverse(), (err) => { // In case of an error throw err. if (err) throw err; }); });
问题原因及修复方案
问题根源
你调用了data.reverse(),这里的data是Buffer类型,它的reverse()方法会反转Buffer中的每一个字节,导致每行的字符被逐个反转,而不是反转行的整体顺序。你已经正确反转了行数组array,但没有用这个反转后的数组去生成写入文件的内容。
修复后的代码
var fs = require('fs'); fs.readFile('help.txt', function(err, data) { if(err) throw err; // 兼容Windows(\r\n)和Linux(\n)的换行符分割 var lines = data.toString().split(/\r?\n/); // 过滤空行,避免文件末尾空行干扰 lines = lines.filter(line => line.trim() !== ''); // 反转行顺序 const reversedLines = lines.reverse(); // 将反转后的行数组拼接为字符串 const outputContent = reversedLines.join('\n'); fs.writeFile('Output.txt', outputContent, (err) => { if (err) throw err; console.log('文件写入完成'); }); });
关键改动说明
- 用
split(/\r?\n/)替代split("\n"),适配不同操作系统的换行格式。 - 增加空行过滤逻辑,避免文件末尾的空行被反转到结果开头。
- 使用反转后的行数组
reversedLines拼接成字符串,而非直接操作原始Buffer。
内容的提问来源于stack exchange,提问作者Mitchell
相关产品推荐
相关产品推荐

