I have a txt file with around 5000 lines in it, I would like to print a random line from that file. I have tried using readline but cant figure out how to choose which line to print using integers. What would be the fastest way to do this without using much memory?
Here is my code
const readline = require("readline");
const fs = require("fs");
const file = readline.createInterface({
input: fs.createReadStream('file.txt'),
output: process.stdout,
terminal: false
});
file.on('line', (line) => {
console.log(line);
})
The straightforward solution would be:
But it might use quite a bit of memory if your file is really large.
so without reading the entire file, off the top of my head - Maybe seek to a random position, then read until you hit \n, and then again read until \n, then split by \n and pick the middle part of the array?
Note- this will break if the last line isn't followed by a new line. (if the random position is in the last two lines)
two approaches here:
const readline = require("readline");
const fs = require("fs");
const file = readline.createInterface({
input: fs.createReadStream('file.txt'),
output: process.stdout,
terminal: false
});
const radnomLineNumber = getRandomInt(5000);
let i = 0;
file.on('line', (line) => {
if (randomLineNumber === i) {
console.log(line);
return;
}
i++;
});