Pick random line from text file

Hi all, I have a text file of jokes, each joke is on a new line in the text file. How can I get node red to pick a random line from the file.

I will be sending the result to a TTS service, I have done this before using an API that served a random joke but how do I get it working using a text file.

Any help would be greatly appreciated.

Use the random note to grab a random number then take your text file and use a split note to split it based on the\in character and create an array out of it. Then you could use the random number to pick them up array the line from the array based on that.

I did manage to get this working using a read file node going to a function node to split into an array and pick a random number from the array.

var joke = msg.payload.split("~");
var rnd = Math.floor(Math.random() * joke.length);
msg.payload = joke[rnd]
return msg;

I took all the line breaks / new line stuff out the text file and replaced them with "~". I just couldn't find anything that worked to split by new line. Tried "/n" (Still learning this lol)

This does work, but it loads the text file in full every time. Is there a better way of doing this?? or is this way acceptable??

Any help, criticism of my crummy code greatly appreciated.

It should be "\n".

Yea I tried /n \n all different things, I think the txt file might have come from excel or csv, I couldn't find anything that worked lol

I did try using the split node but was complaining about some unrecognised characters as well, looked fine to me just looked like a normal txt file.

I use this code, and it works fine for me.

[{"id":"a059aeeda27bd133","type":"csv","z":"40351d051417302b","name":"","sep":".","hdrin":"","hdrout":"none","multi":"mult","ret":"\\n","temp":"","skip":"0","strings":true,"include_empty_strings":"","include_null_values":"","x":970,"y":1980,"wires":[["c6f712e6d57b84fa"]]},{"id":"38f1b2d4755bcc29","type":"file in","z":"40351d051417302b","name":"","filename":"godmorgen.csv","filenameType":"str","format":"utf8","chunk":false,"sendError":false,"encoding":"none","allProps":false,"x":780,"y":1980,"wires":[["a059aeeda27bd133"]]},{"id":"c6f712e6d57b84fa","type":"function","z":"40351d051417302b","name":"function 2","func":"var array = msg.payload; // Definerer arrayet fra payload-objektet\nvar randomIndex = Math.floor(Math.random() * array.length); // Vælger et tilfældigt index i arrayet\nvar randomElement = array[randomIndex]; // Vælger det element, der er på det tilfældige index\n\nmsg.payload = randomElement; // Gemmer det tilfældige element i payload-objektet\nreturn msg; // Returnerer beskeden","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":1100,"y":1980,"wires":[["d0100b8050cffd27"]]}]

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.