Read error with TXT and CSV files. SyntaxError: expected expression, got keyword 'do' at undefined:965:8

‘’’ javascript
let palabras = ;
let palabraActual = “”;
async function setup() {
createCanvas(800, 500);
try {
const respuesta = await fetch(“palabras.txt”);
const texto = await respuesta.text();
palabras = texto
.split(/\r?\n/)
.map(p => p.trim())
.filter(p => p.length > 0);
console.log(“Palabras cargadas:”, palabras.length);
} catch (error) {
console.error(“Error leyendo palabras.txt:”, error);
}
}
function draw() {
background(240);
fill(0);
textAlign(CENTER, CENTER);
textSize(60);
text(palabraActual, width / 2, height / 2);
}
function mousePressed() {
if (palabras.length > 0) {
const indice = floor(random(palabras.length));
palabraActual = palabras[indice];
console.log(
“Índice:”, indice,
“Palabra:”, palabraActual
);
}
}
‘’’
Read error with TXT and CSV files
When loading a “palabras.txt” or “palabras.CSV” file containing 69,327 words using the loadStrings or loadTable function, it indicates that the file has no records and displays the error: “SyntaxError: expected expression, got keyword ‘do’ at undefined:965:8”.
If I use the command await fetch("palabras.txt");, it reads all the data from the file, although it still displays the error: SyntaxError: expected expression, got keyword ‘do’ at undefined:965:8.

Hey,

welcome to the forum! Great to have you.

Did you post your entire Sketch? Is 965:8 a line number?

Do you have different tabs?

Are you sure the file has been found and is loaded?

Chrisir

Welcome to the forum. :smile:

Since you are using p5.js I suggest that you use loadStrings rather than fetch. It has a number of advantages

  • it is a tried and tested method that will work with any ASCII text file
  • it will split the file contents into strings based on the operating system attributes for a new line
  • does not throw an exception for an empty file

So you might try this for your setup

async function setup() {
    createCanvas(800, 500);
    const texto = await loadStrings("palabras.txt");
    palabras = texto
        .map(p => p.trim())
        .filter(p => p.length > 0);
    console.log("Palabras cargadas:", palabras.length);
}

If you continue with fetch then try changing the split pattern to

    palabras = texto
    .split(/\r\n|\n/)
    .map ...

I am not sure where this error is coming from since you do not have any do-while constructs in your code.

Personally I would create a much smaller data file (~12 lines) to check the program logic then go back to the actual (large) file.

It it works with the small test file but then fails with the large file then check to make sure that the file data is not corrupted.