简体   繁体   中英

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

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM