Listing folders and files within them from particular folder in Google drive

I am trying to get the list of files and folders from a particular folder in google drive using node.js. However I am only getting the list of folders and not the files within those folders. What am I doing wrong?

Here is my code.

app.get('/getFF', (req, res) => {
var folderid = <'my folder id'>;
var query = "'" + folderid + "' in parents";

drive.files.list({q: query, fields: 'files(id)'}, (err, resp) => {
    if (err) throw err;
    const files = resp.data.files;
    if (files.length) {
        files.map((file) => {
        console.log(file);
        });
        res.send(files);
    } else {
    resp.send('No files found');
    }
});

})

Answer

I believe your goal and your current situation as follows.

  • You want to retrieve the file list under the specific folder.
  • The specific folder has the subfolders.
  • You want to achieve this using googleapis for Node.js.
  • You have already been able to retrieve the file list using Drive API v3 with googleapis.

Modification points:

  • In the current stage, when drive.files.list({q: query, fields: 'files(id)'}) with var query = "'" + folderid + "' in parents" is used, the file list of the files and folders just under the folder of folderid are retrieved. It seems that this is the current specification. In order to retrieve the file list of all files under the specific folder which has the subfolders, it is required to retrieve the file list from each subfolder.
  • In this answer, I would like to propose to use a library of node-getfilelist for Node.js. This library can retrieve the file list of all files under the specific folder which has the subfolders. I created this library for such situation.

Usage:

1. Install library.

At first, please install the library as follows.

$ npm install --save-dev google-drive-getfilelist

or

$ npm install --global google-drive-getfilelist

2. Sample script.

const getfilelist = require("google-drive-getfilelist");

const topFolderId = "###"; // Please set the top folder ID.
getfilelist.GetFileList(
  {
    auth: auth,
    fields: "files(id)",
    id: topFolderId,
  },
  (err, res) => {
    if (err) {
      console.log(err);
      return;
    }
    const fileList = res.fileList.flatMap(({ files }) => files);
    console.log(fileList);
  }
);
  • In this case, auth is the auth of const drive = google.drive({version: 'v3', auth}).
Result:

When above script is run, the following result is obtained at console.log(fileList);. fileList is the file list of all files under the specific folder which has the subfolders.

[
  { id: '###' },
  { id: '###' },
  ,
  ,
  ,
]

Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *