Read a text file and save it into a list (JavaScript)

Viewed 180

I have a list of nouns in a text file. I would like read this with JavaScript, save it in a variable, and split it into a list of strings (corresponding to each noun). I need these nouns to then create the stimuli for an experiment. This is what I tried, but doesn't seem to work:

function readNamesfromFileandCreateList (audiostim_name){
    //read from file a list of words, save it in a list and and shuffle it (twice for good measure)
    var openedText = await fetch(audiostim_name);
    var words = openedText.split(/\r\n|\n/);
    jsPsych.randomization.shuffle(words); jsPsych.randomization.shuffle(words); 
    return words
}

The errors I get are that .split() is not a function and that my text file cannot be accessed or loaded. I am using a webserver.

1 Answers

Fetch returns a response - you need to call response.text() to get the string that you can split on

function readNamesfromFileandCreateList (audiostim_name){
    //read from file a list of words, save it in a list and and shuffle it (twice for good measure)
    var response = await fetch(audiostim_name);
    var openedText = await response.text(); // <-- changed
    var words = openedText.split(/\r\n|\n/);
    jsPsych.randomization.shuffle(words); jsPsych.randomization.shuffle(words); 
    return words
}
Related