Streaming a file line-by-line in reverse order in Node.js requires a combination of reading the file in chunks, splitting it into lines, and processing them in reverse. However, since Node.js streams typically process data sequentially from the start of the file, reversing the lines while streaming requires special handling. Here's a solution:
Implementation
Read the file usingfsin chunks.
Buffer the data to identify complete lines.
Store lines in an array and reverse their order before emitting them.
Read the file usingfsin chunks.
Buffer the data to identify complete lines.
Store lines in an array and reverse their order before emitting them.
async function streamFileInReverse(filePath) {
// Read the entire file into memory (to reverse it)
const data = await fs.promises.readFile(filePath, 'utf8');
code
// Split file contents into lines and reverse the order
const lines = data.split('\n').reverse();
// Emit lines one by one
for (const line of lines) {
console.log(line); // Replace this with your processing logic
}
}
// Usage
const filePath = './example.txt'; // Replace with your file path
streamFileInReverse(filePath).catch(console.error);
Explanation
fs.promises.readFile: Reads the entire file into memory. While this isn't strictly streaming, it simplifies reversing lines, especially for moderately sized files.
split('\n').reverse(): Splits the file content into lines, reverses the array, and emits them one by one.
Iterating over the reversed lines: You can replaceconsole.logwith other processing or event-based logic.
fs.promises.readFile: Reads the entire file into memory. While this isn't strictly streaming, it simplifies reversing lines, especially for moderately sized files.
split('\n').reverse(): Splits the file content into lines, reverses the array, and emits them one by one.
Iterating over the reversed lines: You can replaceconsole.logwith other processing or event-based logic.
For Large Files
If the file is too large to fit in memory, you can:
Read the file in chunks from the end usingfs.createReadStream.
Buffer the chunks and reverse-process lines as they are identified.
This requires a more complex implementation to handle partial lines across chunks.
Read the file in chunks from the end usingfs.createReadStream.
Buffer the chunks and reverse-process lines as they are identified.
This requires a more complex implementation to handle partial lines across chunks.
Here's anoptimized implementation for large files: