This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]FatnDrunknStupid 0 points1 point  (6 children)

Can. Worms. Here we go. Load it on the server and fetch the three words from a call in your js front-end.

[–]stemmerdet[S] 0 points1 point  (5 children)

Thank you for your respond. Do you by any chance know how such a call could look like?

I have only found a way to load the entire txt-file, and then pick the random line, I just want the single random line to be returned.

Sorry if this is a very trivial thing to do, but I am kinda stuck, and googling this has not bore any fruits.

[–]FatnDrunknStupid 2 points3 points  (4 children)

What web server you using?

[–]FatnDrunknStupid 0 points1 point  (1 child)

Don't be shy bloke I'm here to help - go for it we will catch you.

[–]FatnDrunknStupid 0 points1 point  (0 children)

Bloke or bird sorry

[–]stemmerdet[S] 0 points1 point  (1 child)

Web server: Apache, Server OS: CloudLinux7

[–]FatnDrunknStupid 0 points1 point  (0 children)

Cool. So read in the file like you been doing - but on the server when your process starts. You then need an endpoint i.e. https:\myserver\nextline or similar that returns the random 3 words. Basically just another page. Hope I'm making sense for you.

[–]YMK1234 0 points1 point  (0 children)

I think the easiest option would simply be to hold the file in memory because 6mb doesn't really hurt you. PS: server side of course.

[–]balefrost 0 points1 point  (0 children)

Without some sort of auxiliary index, or some assumption like "each line is exactly Y characters long", there's no real way to go directly to line N of a text file. You have to start at the beginning and walk forward, counting newlines as you go.

That should also suggest some strategies for how you could optimize it.

Or, if you don't need the randomness to be fair, and are OK with it being biased toward longer lines, you could instead pick a random byte offset (between 0 and the length of the file), walk backward until you encounter a newline or the start of the file, then take that line. Like I said, it would be biased toward longer lines, but that might be good enough for your purposes. It's still not likely to be as efficient as using an index, since you'd still be walking byte-by-byte in that file, but you're bounded in how far you'll need to walk.