node.jsgoogle-apigoogle-drive-apigoogle-api-nodejs-client

Retrieving the contents of a folder by folder ID using Google Drive API


I want to retrieve the contents of a specific folder on Google Drive using node.js and the googleapis and google-auth-library packages. The problem is that while the folder exists and can be found using the .get method, it appears to be empty when it shouldn't:

drive.files.list({
    q: `'${dataSource.folder_id}' in parents`,
    fields: 'files(id, name, mimeType)'
}, (err, res) => {
    if (err) {
        console.error('Error retrieving folder contents:', err);
        return;
    }
          
    const contents = res.data.files;
    if (contents && contents.length > 0) {
        console.log('Contents of the folder:');
        contents.forEach(file => {
             console.log('File Name:', file.name);
             console.log('File ID:', file.id);
             console.log('File Type:', file.mimeType);
             console.log('---');
        });
    } else {
        console.log('The folder is empty.');
    }
});

Use case: I want to retrieve the files in Google Drive for a specific folder and that folder only. The folder gets created programmatically when the user enables the Google Drive authentication

Update: It was a permissions problem, I was missing: 'https://www.googleapis.com/auth/drive.readonly'. However, this now means I can retrieve ALL files from the user, where I only wanted access to a specific folder. Is this even possible?


Solution

  • However, this now means I can retrieve ALL files from the user, where I only wanted access to a specific folder. Is this even possible?

    No drive permissions is all or nothing with drive.readonly you have read only access to all the files on a users drive account.

    you could try drive.file but that will only give you access to files that your app has created.