Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
1.5 kB
2
Indexable
function trimFile(filepath, limit) {
    const tempFilePath = filepath + '.tmp';
    const writeStream = fs.createWriteStream(tempFilePath);
    const readlineMachine = readline.createInterface({
        input: fs.createReadStream(filepath),
        crlfDelay: Infinity,
    });
    let linesCount = 0;
    let linesBuffer = [];
    readlineMachine.on('line', (line) => {
        linesBuffer.push(line);
        linesCount++;
        if (linesCount >= limit) {
            linesBuffer.shift();
        }
    });
    readlineMachine.on('close', () => {
        for (const line of linesBuffer) {
            writeStream.write(line + '\n');
        }
        writeStream.end(() => {
            fs.rename(tempFilePath, filepath, (err) => {
                if (err) {
                    console.error('Error renaming file: ' + tempFilePath
                        + ' to ' + filepath, err);
                }
                else {
                    console.log('Renamed file: ' + tempFilePath
                        + ' to ' + filepath);
                }
            });
        });
        console.log('Trimmed file: ' + filepath);
    });
    readlineMachine.on('error', (err) => {
        console.error('Error reading file:' + filepath, err);
        readlineMachine.close();
        writeStream.end();
    });
    writeStream.on('error', (err) => {
        console.error('Error writing file:' + filepath, err);
        readlineMachine.close();
        writeStream.end();
    });
}