Skip to content
Advertisement

Read text file line by line and select random line javascript

I am trying to read a text file filepath = "data/words.txt" and randomly select a line to print in the console.

I tried to do:

function generateRandomWord() {
  var file = new File(filepath);
  let fileReader = new FileReader();
  const data = fileReader.readAsText(file);
  var lines = data.split("n");

  var line = lines[Math.floor(Math.random() * lines.length)]; //select a random line from txt file (a random word)
  console.log(line);
}

However, I can’t seem to get the file to read.

Advertisement

Answer

if you want read a text file from the path you need run your code such as node.js environment; but if you using HTML and browser to pick file from input, continue .

add some html element to pick file and generate text from picked file :

<input type="file" onchange="FileReader(this.files[0])" />
<button onclick="RandomText(TEXT)">Generate</button>

and now add this js script :

var TEXT = "";
async function FileReader(file) {
  TEXT = await file.text();
}
function RandomText(text) {
  const textArray = text.split("n");
  const randomKey = Math.floor(Math.random() * textArray.length);
  console.log(textArray[randomKey]);
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement