There’s no built-in Node.js stream that can read a file line-by-line in reverse order, so you have a couple of approaches depending on your constraints (e.g. file size, memory limits, complexity allowed):
If the file is not extremely large, the simplest solution is to just read the entire file into memory, split it into lines, reverse that array, and then emit each line from your custom stream. For smaller files, this is perfectly acceptable.
Not truly streaming from disk; it’s a batch process first, then stream.
Requires loading the entire file into memory.
Not truly streaming from disk; it’s a batch process first, then stream.
Streaming from the End of the File (Manual Implementation)
For very large files, you might want a true streaming solution without loading everything into memory at once. This is trickier, because you have to:
Open the file atit to get its size.
Start reading it in chunks from the end backwards.
Buffer data until you find newline characters.
Each time you find a newline, you know you’ve ended a line. Extract that line and emit it.
Continue until you reach the beginning of the file.
Open the file andfs.statit to get its size.
Start reading it in chunks from the end backwards.
Buffer data until you find newline characters.
Each time you find a newline, you know you’ve ended a line. Extract that line and emit it.
Continue until you reach the beginning of the file.
Key Steps for a Manual Reverse Reader:
fs.openthe file.
fs.statto getsize.
Set a chunk size (e.g., 64).
Starting fromposition = size - chunkSize(or less if size < chunk), read backwards in a loop:Usefs.readto read a block into a buffer.Prepend this buffer to a "working string" of collected data.Check for newline characters in the collected data from the end going forward.Each newline found means you’ve isolated a "line" that can be emitted.Update the position, move further back, and continue until you’ve covered the entire file.
Usefs.readto read a block into a buffer.
Prepend this buffer to a "working string" of collected data.
Check for newline characters in the collected data from the end going forward.
Each newline found means you’ve isolated a "line" that can be emitted.
Update the position, move further back, and continue until you’ve covered the entire file.
fs.openthe file.
fs.statto getsize.
Set a chunk size (e.g., 64).
Starting fromposition = size - chunkSize(or less if size < chunk), read backwards in a loop:
Usefs.readto read a block into a buffer.
Prepend this buffer to a "working string" of collected data.
Check for newline characters in the collected data from the end going forward.
Each newline found means you’ve isolated a "line" that can be emitted.
Update the position, move further back, and continue until you’ve covered the entire file.
Usefs.readto read a block into a buffer.
Prepend this buffer to a "working string" of collected data.
Check for newline characters in the collected data from the end going forward.
Each newline found means you’ve isolated a "line" that can be emitted.
Update the position, move further back, and continue until you’ve covered the entire file.
async function readLinesReverse(filePath) {
const fd = await fs.promises.open(filePath, 'r');
const stat = await fd.stat();
let fileSize = stat.size;
const chunkSize = 65536; // 64KB
let position = fileSize;
let leftover = '';
while (position > 0) {
const readSize = Math.min(chunkSize, position);
position -= readSize;
code
const { buffer, bytesRead } = await fd.read(Buffer.alloc(readSize), 0, readSize, position);
// Convert buffer to string
let chunkStr = buffer.toString('utf8');
// Prepend leftover (we're reading backwards, so leftover is ahead in the file)
chunkStr += leftover;
// Split by newline
const lines = chunkStr.split('\n');
// The last element of lines might be partial if we haven’t reached another newline yet
leftover = lines.shift(); // Actually, since we are reading from the back, handle carefully:
// Explanation:
// - After reading a chunk, we attach leftover at the end.
// - lines array now contains lines split by \n. The FIRST element (lines[0]) is actually
// the line closest to the end (since we appended leftover at the end).
// We actually want to reverse thinking: The last chunk read is "earlier" in the file.
// A robust approach would be:
// Let's assume newline at the end of file may not exist. We'll handle that after finishing all reads.
// lines now looks like [partialLineFromThisChunk, lineN, lineN-1, ..., lineAtStart]
// But since we appended leftover at the end, the last element in lines array is the earliest line in the file chunk.
// Actually, to simplify, consider this approach:
// - Reverse lines at this point because we are effectively collecting from the end:
lines.reverse();
// The first element in reversed order might be incomplete (the leftover for the next iteration)
leftover = lines.shift() + leftover; // Combine partial lines together
// Now lines contains complete lines from the chunk in reverse order
for (const l of lines) {
if (l !== '') {
// Emit this line (in correct reversed order)
console.log(l);
}
}
}
// After the loop, leftover might contain the very first line (if it wasn't empty)
if (leftover !== '') {
console.log(leftover);
}
Requires careful logic for handling partial lines at chunk boundaries.
More complex code.
Requires careful logic for handling partial lines at chunk boundaries.
Use a Third-Party Module
If you prefer not to implement the logic yourself, you can use an NPM package that already provides this functionality. For example, there’s a package calledreverse-line-readerthat does exactly this for you: