node.js - 之后如何从文本文件中 node.js 中的特定行位置删除行
问题描述
我想在第 7 行之后删除所有行 如何使用 node.js 和 fs 执行此操作
const fs = require('fs');
文本文件 (.txt)
Time Schedule for
Remind before
Channel to remind
Last edit
Last update
Reminders
1) fr 4:9 7:0 abcd 123
2) mo 5:0 7:0 123 ajk
解决方案
您可以使用转换流,在达到所需的行数后停止读取文件,并仅写入转换后的内容,即第 n 行之前的内容。
const fs = require('fs');
const { Transform } = require('stream');
const clipLines = maxLines => {
// Get new line character code [10, 13]
const NEWLINES = ['\n', '\r\n'].map(item => item.charCodeAt(0));
let sourceStream;
let linesRemaining = maxLines;
const transform = new Transform({
transform(chunk, encoding, callback) {
const chunks = [];
// Loop through the buffer
for(const char of chunk) {
chunks.push(char); // Move to the end if you don't want the ending newline
if(NEWLINES.includes(char) && --linesRemaining == 0) {
sourceStream.close(); // Close stream, we don't want to process any more data.
break;
}
}
callback(null, Buffer.from(chunks));
}
});
transform.on('pipe', source => {
sourceStream = source
if(maxLines <= 0)
source.close();
});
return transform;
}
fs.createReadStream('test.txt')
.pipe(clipLines(7))
.pipe(fs.createWriteStream('out.txt'))
使用流,允许您处理大文件,而不会达到内存限制。
推荐阅读
- android - Glide 显示旧加载的图像而不是新的
- react-native - 反应本机重用组件问题,未调用 componentDidMount
- windows - 如何从命令中提取用户名作为变量
- javascript - String.split 函数无法正常处理某些文本
- python - 我想要超链接到相同长度的excel中的一列的链接列表
- c++ - 置换二维数组中的元素
- python - 为什么即使我使用 sparse_categorical_crossentrpy,我也会收到“收到超出 [0, 1) 有效范围的标签值 6”?
- perl - 如何在使用不存在的哈希键声明数组后使 Perl 死亡
- python - 如果所需的文本也在单元格中,则尝试在表格单元格中选择链接文本
- android - 在 BottomNavigationView 的片段替换中使用 onSaveInstanceState