之后如何从文本文件中的node.js中的特定行位置删除行

时间:2018-07-19 13:51:59

标签: node.js fs

在第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

1 个答案:

答案 0 :(得分:0)

您可以使用 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'))

使用流,可以处理大文件,而不会达到内存限制。