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:
JavaScript
x
10
10
1
function generateRandomWord() {
2
var file = new File(filepath);
3
let fileReader = new FileReader();
4
const data = fileReader.readAsText(file);
5
var lines = data.split("n");
6
7
var line = lines[Math.floor(Math.random() * lines.length)]; //select a random line from txt file (a random word)
8
console.log(line);
9
}
10
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 :
JavaScript
1
3
1
<input type="file" onchange="FileReader(this.files[0])" />
2
<button onclick="RandomText(TEXT)">Generate</button>
3
and now add this js script :
JavaScript
1
10
10
1
var TEXT = "";
2
async function FileReader(file) {
3
TEXT = await file.text();
4
}
5
function RandomText(text) {
6
const textArray = text.split("n");
7
const randomKey = Math.floor(Math.random() * textArray.length);
8
console.log(textArray[randomKey]);
9
}
10