Computer Programming
For Psychologists

Adding images from a folder in a jsPsych experiment


When running an experiment that involves a lot of images on a local computer, one procedure to get the images in your experiment is to write a little bit of code that lists all the images in a specified folder. Unfortunately, this convenient approach does not work with JavaScript. For security reasons, client-side JavaScript is not allowed to access the file system, and listing the content of a folder is therefore impossible.

In these cases, my solution is to use a hybrid approach where I list the content of the folder that I intend to use on my local computer and then generate a string that I can copy-paste into my jsPsych code. 

Specifically, suppose that I want to create an image-button-response trial for every image in my ExperimentalImages folder. For that I would like to have all the image names in an array so that I can loop over the array and create the corresponding trials as follows:

let images = [];

for(let i = 0; i < images.length; ++i){
   let imageTrial = {
      type: jsPsychImageButtonResponse,
      stimulus: 'ExperimentalImages\' + images[i]
   }
   timeline.push(imageTrial)
}

To fill the images array, I would use the following Python code:

import json
import os

stimulus_folder = r'C:\MyExperiment\ExperimentalImages'
stimuli = []

for stimulus in os.listdir(stimulus_folder):
   if '.jpg' in stimulus:
      stimuli.append(stimulus)
        
parameters = "let images = " + json.dumps(stimuli) + ";"

This Python code scans the content of stimulus_folder, and adds any files that have the .jpg extension to a list. The final line of code creates a string that is valid JavaScript code, and the content of that string can be copy-pasted into my JavaScript code.