之后如何从文本文件中 node.js 中的特定行位置删除行
How remove lines afterwards from a specific line location in node.js in text file
我想删除第 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
您可以使用Transform流,在达到所需的行数后停止读取文件,只写入转换后的内容,即内容直到第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'))
使用流,允许您处理大文件,而不会达到内存限制。
我想删除第 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
您可以使用Transform流,在达到所需的行数后停止读取文件,只写入转换后的内容,即内容直到第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'))
使用流,允许您处理大文件,而不会达到内存限制。