ArticleZip > Is There A Way To Return A List Of All The Image File Names From A Folder Using Only Javascript

Is There A Way To Return A List Of All The Image File Names From A Folder Using Only Javascript

Do you ever find yourself needing to retrieve a list of all image file names from a specific folder using JavaScript? Well, you're in luck because I'm here to guide you through the process step by step.

To accomplish this task, we can utilize the File System Access API in modern browsers to access files and directories securely. This API allows JavaScript code running in a web application to read and save files on the user's device. Before we begin, make sure your browser supports this API.

First, we need to request permission from the user to access the file system. This is an important security measure to ensure that the user is in control of the files being accessed. Your code should include a prompt asking for permission to access the folder containing the images.

Once permission is granted, we can use the API to retrieve a list of all files within the specified folder. We will focus on extracting only the image file names from the list. Here's a sample script to help you with this:

Javascript

async function getImageFileNamesFromFolder() {
  const folderHandle = await window.showDirectoryPicker();
  const imageFiles = [];
  
  for await (const entry of folderHandle.values()) {
    if (entry.kind === 'file' && entry.name.match(/.(jpg|jpeg|png|gif)$/i)) {
      imageFiles.push(entry.name);
    }
  }

  return imageFiles;
}

getImageFileNamesFromFolder()
  .then(imageFiles => {
    console.log('Image file names in the folder:', imageFiles);
  })
  .catch(error => {
    console.error('An error occurred:', error);
  });

In the script above, we define an asynchronous function `getImageFileNamesFromFolder` that requests a directory picker dialog to select the folder containing image files. We then iterate over each entry in the folder, checking if it is a file and has an image file extension (e.g., jpg, jpeg, png, gif). If so, we add the file name to the `imageFiles` array.

After running the function `getImageFileNamesFromFolder`, the image file names will be logged to the console for you to view. Feel free to modify the script according to your specific requirements.

Remember to handle errors gracefully to provide a smooth user experience. Error handling is crucial, especially in asynchronous operations like file system access.

By following these steps and understanding the File System Access API, you can easily retrieve a list of image file names from a folder using only JavaScript. Happy coding!