I’m trying to pull file details from my Google Drive and put them into a Google Sheet. I found some code online but it’s not working. Here’s what I’m dealing with:
function getFileInfo(folderName) {
let folder = DriveApp.getFoldersByName(folderName).next();
let files = folder.getFiles();
let sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(['Name', 'Created', 'Size', 'Link', 'Download', 'Info', 'Kind']);
while (files.hasNext()) {
let file = files.next();
if (file.getMimeType() !== MimeType.GOOGLE_SHEETS) {
let row = [
file.getName(),
file.getCreationDate(),
file.getSize(),
file.getUrl(),
`https://drive.google.com/uc?export=download&id=${file.getId()}`,
file.getDescription(),
file.getMimeType()
];
sheet.appendRow(row);
}
}
}
When I run this, I get an error saying it can’t find the ‘next’ function for Files. Any ideas on how to fix this or a better way to do what I’m trying to do? Thanks!
The issue you’re encountering is likely due to the iterator method. Instead of using ‘while’ and ‘next()’, you can simplify your code with a ‘for…of’ loop. Here’s a modified version that should work:
function getFileInfo(folderName) {
let folder = DriveApp.getFoldersByName(folderName).next();
let files = folder.getFiles();
let sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(['Name', 'Created', 'Size', 'Link', 'Download', 'Info', 'Kind']);
for (let file of files) {
if (file.getMimeType() !== MimeType.GOOGLE_SHEETS) {
let row = [
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl(),
`https://drive.google.com/uc?export=download&id=${file.getId()}`,
file.getDescription(),
file.getMimeType()
];
sheet.appendRow(row);
}
}
}
This should resolve the ‘next’ function error and allow you to iterate through your files successfully. Let me know if you encounter any other issues.
I’ve had similar issues when working with Google Drive API. One thing that helped me was using the getFileIterator() method instead of getFiles(). It’s more reliable for handling large folders. Here’s a tweaked version of your code that worked for me:
function getFileInfo(folderName) {
let folder = DriveApp.getFoldersByName(folderName).next();
let fileIterator = folder.getFileIterator();
let sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(['Name', 'Created', 'Size', 'Link', 'Download', 'Info', 'Kind']);
while (fileIterator.hasNext()) {
let file = fileIterator.next();
if (file.getMimeType() !== MimeType.GOOGLE_SHEETS) {
let row = [
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl(),
`https://drive.google.com/uc?export=download&id=${file.getId()}`,
file.getDescription(),
file.getMimeType()
];
sheet.appendRow(row);
}
}
}
This approach has been more stable in my experience, especially when dealing with folders containing numerous files. Give it a try and see if it resolves your issue.