p5.js is a frontend library. That is, it just controls what you can see and interact with in the browser, and doesn’t have access directly to the filesystem. The code you posted is for use with backend code, like a node.js server. It is possible for frontend code and backend code to communicate with each other, but you won’t be able to run this code directly from your p5.js sketch. More on frontend vs backend code here.
To answer your question directly, from the p5.js sketch itself, there is not a way to list the files in your filesystem or folder.
If you are working in the back end, then let us know. For demonstration purposes (I haven’t tried this) you should be able to run a local host in your computer, then you use js to access/inquire your local server to get this info for you. As I said, this is good for demonstration purposes but it might need to be reconsider based on your final goal.
depending on what you are trying to do there are some ways to kind of get around having to do this on the back end with having a user select a file with a file picker before using the file in JS. This way it’s on user choice and not penetrating the secure walls of the browser: https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications
Hello, first of all thanks for the help, what I’m trying to do is a function that loads a folder of images.
The idea is not to directly use the loadImage function (file), it is better to use the new function loadImages (
path), where a location relative to the script is passed as parameter, for example “/ data / images /” and the function is responsible for generating a list of files and loading them into an image matrix.
An example of this has already been created for java processing:
PImage[] loadImages(String nameFolder) {
java.io.File folder = new java.io.File(dataPath("")+"/"+nameFolder);
String[] filenames = folder.list();
PImage[] img = new PImage[filenames.length];
for (int i = 0; i < filenames.length; i++) {
img[i] = loadImage(dataPath("") + "/" + nameFolder + "/" + filenames[i]);
}
return img;
}
If you are unable to use the file picker in the HTML5 spec, you’ll have to use node.js and fs.readdir which run on the backend and can have access to the filesystem. check out @lmccart’s post above for all the details.