In our previous lesson (Part 42), we explored how to use Folder.createFile() to automatically create new files inside a specific Google Drive folder, such as “Recommended Scenic Drive Routes.txt”!
Once you start automating Google Drive with Google Apps Script (GAS), the next step you’ll naturally want to tackle is listing every single file inside a target folder and logging all of them directly into a Google Spreadsheet.
Imagine manually copying and pasting the file name and URL for hundreds of travel photos taken across Hokkaido, client PDF invoices, or presentation decks into a spreadsheet one by one. It sounds exhausting, doesn’t it?
That is why in Part 43, we are diving deep into an essential Google Apps Script method: Folder.getFiles(), which retrieves every file in a folder automatically in bulk!
At first glance, concepts like “Iterators” and while loops might feel a bit intimidating. Don’t worry! I’ll break them down using intuitive, everyday analogies so anyone can follow along. Let’s jump right in!
1. What Is Folder.getFiles()?
Folder.getFiles() is a method that retrieves all files stored inside a target folder (Folder object) as a FileIterator object.
Basic Code Structure
// Retrieve the list of files (Iterator) inside a folder
var files = folder.getFiles();
When we break down the dot (.) syntax, the structure is remarkably simple:
folder: The target Google Drive folder object obtained via methods likeDriveApp.getFolderById()(covered in Part 41)..getFiles(): Bundles all the files located inside that folder and prepares them to be retrieved. Note the pluralsat the end of the method name!
Key Concept: How an “Iterator” Differs from an “Array”
Whenever we worked with collections of data in earlier lessons, we used Arrays (introduced in Part 7). An array is like a bento box: items are neatly indexed like [data1, data2, data3], and you can instantly grab any element with an index like array[0].
However, Folder.getFiles() does not return a standard JavaScript Array. Instead, it returns a special object called a FileIterator.
This is often where beginners get confused, so let’s visualize it using a conveyor-belt sushi restaurant or a capsule toy dispenser!
| Concept | Array | Iterator (FileIterator) |
| Analogy | Divided Bento Box | Conveyor-Belt Sushi / Capsule Dispenser |
| Data State | All items are visible and already in your hands | Items wait in the kitchen (Google Drive) and arrive one by one |
| Access Method | Directly pick via index like array[0] |
Check “Is there a next plate?” and take one item at a time |
| Total Count | Instantly available via array.length |
Unknown until you pull every single item out to the end |
A Google Drive folder might hold just three files or tens of thousands of large files. If GAS attempted to load all of them into memory at once, your script could freeze. By returning an iterator (a conveyor belt), GAS lets your program process items smoothly one at a time.
To pull files off this “conveyor belt,” we always use a pair of complementary methods:
files.hasNext(): Checks “Is there another file (plate) coming down the belt?” (Returnstrueorfalse).files.next(): Takes the next file (plate) off the belt and hands it to you.
Once you grasp this sequence, you’re ready to master Folder.getFiles()!
2. STEP 1: Set Up the “Hokkaido Scenery Photos” Folder and Spreadsheet
Let’s prepare our workspace before running any code!
In this hands-on tutorial, we will retrieve a list of files from a folder named “Hokkaido Scenery Photos” and write their details into a Google Spreadsheet.
Step-by-Step Instructions
1. Create a Practice Folder in Google Drive
Open Google Drive and create a new folder.
- Folder Name:
Hokkaido Scenery Photos - Upload or create 3 to 5 test files (images or text files) inside this folder.
- Examples:
Blue Pond in Biei.jpg,Autumn Leaves in Jozankei.png,Snowy Odori Park.jpg(dummy files are completely fine).
- Examples:
2. Copy Your Folder ID (Review from Part 41!)
Open your newly created “Hokkaido Scenery Photos” folder and inspect the URL in your browser’s address bar.
The alphanumeric string located after https://drive.google.com/drive/folders/ (e.g., 1a2b3c4d5e6f...) is your Folder ID. Copy this string to your clipboard.
3. Create a Destination Google Spreadsheet
- Create a new Google Spreadsheet and name it
Hokkaido Photo File List. - Enter the following header labels in row 1:
- Cell A1:
File Name - Cell B1:
URL - Cell C1:
Last Updated
- Cell A1:
Your setup is complete!
3. STEP 2: [Hands-On] Export the File List to Google Sheets
Now open the Apps Script editor from your spreadsheet’s top menu by clicking Extensions > Apps Script and prepare to write the script.
1. Enter the Script
Delete any boilerplate code inside the editor and paste the following snippet (make sure to replace YOUR_FOLDER_ID with your actual folder ID):
function listHokkaidoPhotos() {
// 1. Get the target spreadsheet and active sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
// 2. Get the target folder (Hokkaido Scenery Photos) by ID
var folderId = "YOUR_FOLDER_ID"; // ← Replace with your actual folder ID
var folder = DriveApp.getFolderById(folderId);
// 3. Retrieve the file iterator from the folder
var files = folder.getFiles();
// 4. Loop as long as there is another file on the conveyor belt
while (files.hasNext()) {
// Retrieve the next file from the iterator
var file = files.next();
// Extract file attributes
var fileName = file.getName(); // File name
var fileUrl = file.getUrl(); // Web URL of the file
var lastUpdated = file.getLastUpdated(); // Last updated timestamp
// Append the row to the bottom of the sheet using appendRow() from Part 7!
sheet.appendRow([fileName, fileUrl, lastUpdated]);
}
// 5. Output completion message to execution log
Logger.log("Successfully exported the list of files in the folder!");
}
2. Line-by-Line Code Breakdown
Let’s break down the essential components for beginners:
var files = folder.getFiles();- Fetches the files within the folder and assigns them as a “conveyor-belt iterator” to the variable
files. At this stage, individual file names or URLs have not been extracted yet.
- Fetches the files within the folder and assigns them as a “conveyor-belt iterator” to the variable
while (files.hasNext()) { ... }- A
whileloop is a core programming construct that continuously runs the enclosed block as long as its condition evaluates totrue. - As long as
files.hasNext()reports “Yes, there is another file available (true)”, the code inside the curly braces{ }executes. When no files remain, it returnsfalse, and the loop terminates cleanly.
- A
var file = files.next();- Pulls the next individual
Fileobject from the iterator into the variablefile. Calling methods like.getName()or.getUrl()on thisfileallows us to extract its name and link.
- Pulls the next individual
sheet.appendRow([fileName, fileUrl, lastUpdated]);- This is the handy method we covered in Part 7! It packages our data into an array
[ ]and automatically appends a new row at the bottom of the sheet.
- This is the handy method we covered in Part 7! It packages our data into an array
3. Save and Run the Script
- Click the Save icon (floppy disk) at the top of the editor.
- Confirm that the selected function is set to
listHokkaidoPhotos, then click Run. - When running for the first time, Google will display an authorization prompt requesting permission to access Google Drive. Grant access following the steps outlined in Part 2.
- Switch back to your Google Spreadsheet and verify the results!
[Verifying Execution Results]
If row 2 onwards is populated with file names like “Blue Pond in Biei.jpg”, along with their corresponding URLs and modification dates, congratulations! Your automation worked perfectly.
4. How while (files.hasNext()) and files.next() Work Step-by-Step
To clarify how an iterator behaves during each iteration of a while loop, let’s trace through a practical scenario step by step.
Suppose your folder contains exactly two files (File A and File B).
[Initial State]
Belt queue: [ File A ] -> [ File B ]
- Iteration 1 Check
files.hasNext()➡ “File A is up next! (true)”- Action:
var file = files.next();➡ Retrieves File A and appends it to the spreadsheet.
- Iteration 2 Check
files.hasNext()➡ “File B is up next! (true)”- Action:
var file = files.next();➡ Retrieves File B and appends it to the spreadsheet.
- Iteration 3 Check
files.hasNext()➡ “No files remaining! (false)”- Action: The loop exits immediately.
Whether a folder holds 5 files or 500 files, while (files.hasNext()) processes every file automatically until the end without requiring you to count them beforehand. That is the true power of iterators in Google Apps Script!
5. 4 Common Pitfalls for Beginners and How to Fix Them
Here are four frequent pitfalls developers encounter when combining Folder.getFiles() with while loops, along with their solutions.
Pitfall 1: Attempting to Use files.length or files[0]
This is the most common mistake made by developers accustomed to standard arrays.
// ✕ Incorrect usage (Iterators do not have length or index access like [0]!)
Logger.log("Number of files: " + files.length); // returns undefined
var firstFile = files[0]; // Error or unexpected behavior
[Solution]
Remember: when extracting items from an iterator, always use the standard pair of while (files.hasNext()) and files.next()!
Pitfall 2: Calling files.next() Multiple Times Within a Single Loop
Calling next() multiple times in one iteration causes your script to skip every other file!
// ✕ Incorrect usage (Calling next() twice in the same iteration)
while (files.hasNext()) {
Logger.log("File name: " + files.next().getName()); // Pulls file #1
var url = files.next().getUrl(); // ★ Pulls file #2! File #1's URL is lost
}
[Solution]
Call var file = files.next(); once at the top of the loop, store the result in a variable, and reference that variable for all subsequent properties.
Pitfall 3: Forgetting Parentheses on hasNext() (Causing Infinite Loops)
If you omit the parentheses and write files.hasNext, JavaScript evaluates the function reference itself as truthy, which can cause an endless loop that never stops running!
// ✕ Incorrect (Missing parentheses)
while (files.hasNext) { ... }
// ◯ Correct (Includes method call parentheses)
while (files.hasNext()) { ... }
Because hasNext() is an active method that checks folder status, always make sure to include closing parentheses ().
Pitfall 4: What Happens When Running on an Empty Folder?
If you call folder.getFiles() on an empty folder, it will not throw an error.
The first files.hasNext() check immediately evaluates to false, meaning the body of the while loop is skipped safely. You do not need to write extra defensive guards to handle empty folders.
6. Summary and What’s Coming Next
In this lesson, we mastered Folder.getFiles() to automatically list files inside a Google Drive folder and learned how to handle iterators with while loops.
Key Takeaways for Today
Folder.getFiles()returns an Iterator (conveyor belt), not an Array.- Use
files.hasNext()to check if another file is available. - Use
files.next()to retrieve the next file item. - Process items using the standard pattern:
while (files.hasNext()) { ... }. - Never invoke
files.next()more than once per loop iteration.
With this workflow, you can now catalog, organize, and inspect files scattered across Google Drive straight into Google Sheets!
Now that you can list files dynamically, wouldn’t it be great to automatically duplicate template files to generate new documents on demand?
In Part 44, we will cover File.makeCopy() to duplicate files with precision!
We’ll use a “Hokkaido Trip Rental Car Booking Confirmation Template” to demonstrate how to copy and generate ready-to-use booking documents with a single click. Stay tuned for the next post!
