I have no idea on how to do this. Where should I start? I have googled this and not one result came up on how to pull a random line from a text file.
The only thing I have found is https://github.com/chrisinajar/node-rand-line, however it doesn't work. How can I read a random line from a text file?
You would probably want to look at the node.js standard library function for reading files, fs.readFile, and end up with something along the lines of:
//note this will be async
function getRandomLine(filename){
fs.readFile(filename, function(err, data){
if(err) throw err;
var lines = data.split('\n');
/*do something with */ lines[Math.floor(Math.random()*lines.length)];
})
}
If reading the whole thing and splitting isn't an option, then maybe have a look at this stack overflow for ideas.
I don't have Node handy to test code, so I can't give you exact code, but I would do something like this:
Note that this isn't entirely random. Longer lines will be weighted more heavily, but it is the only way to do it without reading the whole file to get a count of lines.
This method allows you to get a "random" line without keeping the whole file in memory.
I can give you a suggestion as I don't have any demo code
buffered reader
int returnRandom(arraySize)
0
to arraySize