Kartik Gautam
Kartik Gautam

Reputation: 55

What is correct syntax of retrieving next page in google drive API through nextPageToken

I was working on an app which lists files of google drive through making requests to a nodeJs API, to get all the files present in drive i am required to request another set of files through this API, but i can't figure out what is correct way to request next page of files using nextPageToken received from previous drive.files.list({}). I searched in documentation but i can't find find any example on this use case. Below is code which i am using, but this code is just returning same 10 files again & again.

..other code here..
drive.files.list({
    orderBy: 'name',
    q: "", 
    nextPageToken:req.body.pageToken, // req.body.pageToken is nextPageToken got in previous requests 
    pageSize: 10,
    fields: 'nextPageToken, files(id, name)',
}, (err, resp) => {
..other code here..

Upvotes: 2

Views: 2061

Answers (1)

Tanaike
Tanaike

Reputation: 201553

I believe your goal and situation as follows.

  • You want to retrieve all files as a list of your Google Drive using googleapis for Node.js.
  • You have already been able to retrieve the file list using Drive API.
    • Your drive can be used for retrieving the file list from your Google Drive.

Modification points:

  • nextPageToken is pageToken.
  • Maximum pageSize is 1000. In this case, when 1000 is used, the number of use of Drive API can be reduced.
  • In order to use nextPageToken, in this answer, I would like to propose to use do while loop.

When your script is modified, it becomes as follows.

Modified script:

async function main(auth) {
  const drive = google.drive({ version: "v3", auth });

  const fileList = [];
  let NextPageToken = "";
  do {
    const params = {
      // q: "",  // In this case, this is not required.
      orderBy: "name",
      pageToken: NextPageToken || "",
      pageSize: 1000,
      fields: "nextPageToken, files(id, name)",
    };
    const res = await drive.files.list(params);
    Array.prototype.push.apply(fileList, res.data.files);
    NextPageToken = res.data.nextPageToken;
  } while (NextPageToken);

  console.log(fileList.length);  // You can see the number of files here.
}
  • drive.files.list returns Promise. So you can use the script like above.

Reference:

Upvotes: 3

Related Questions