Grabbing a random line from file

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:

  1. Get the file size in bytes, pick a random byte offset
  2. Open the file as a stream
  3. Use this snippet to emit lines (or readline, but last I used it had a nasty bug where it essentially didn't work)
  4. Keep track of your position in the file as you read. As you pass your chosen offset, select that line and return it.

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

  1. Read the file line by line using buffered reader
  2. Store every line in a String array
  3. Create a method int returnRandom(arraySize)
  4. Pass the array size in to the function
  5. Calculate a random number between 0 to arraySize
  6. Return the random number
  7. Print the given index from your string array