首页 > 解决方案 > 之后如何从文本文件中 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

标签: node.jsfs

解决方案


您可以使用转换流,在达到所需的行数后停止读取文件,并仅写入转换后的内容,即第 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'))

使用流,允许您处理大文件,而不会达到内存限制。


推荐阅读