Home > OS >  How do I use Google Drive V3 to create a folder?
How do I use Google Drive V3 to create a folder?

Time:09-28

I am trying to create a folder in my Google Drive but I'm really struggling as the official documentation seems to be incorrect or out if date?

My code is as follows (google-drive.ts):

const scopes = ["https://www.googleapis.com/auth/drive"];

const auth = new google.auth.JWT(
  process.env.CLIENT_EMAIL,
  undefined,
  process.env.PRIVATE_KEY,
  scopes,
);

auth.authorize((err) => {
  if (err) {
    console.log(new Error(`Error: ${err}`));
  } else {
    console.log("Connection established with Google API");
  }
});

export const createFolder = async () => {
  const drive = google.drive({ version: "v3", auth });
  
  const fileMetaData = {
    name: "Invoices",
    mimeType: "application/vnd.google-apps.folder",
  };

  await drive.file.create({
    fields: "id"
    resource: fileMetaData //This is where the error is, maybe it is because of Typescript but it says resource doesn't exist?
  });
};

So basically when I try to create a folder with file.create(), as per the official documentations, I'm supposed to put the fileMetaData in resource, however Typescript is not letting me do it as it doesn't exist.

Also, just a side question. Is my auth correct? I used JWT instead of 0Auth because the credentials json I downloaded from the Google console didn't give me a 'secret'.

CodePudding user response:

When I saw your script, I thought that there are modification points in your script. So, how about the following modification?

From:

export const createFolder = async () => {
  const drive = google.drive({ version: "v3", auth });
  
  const fileMetaData = {
    name: "Invoices",
    mimeType: "application/vnd.google-apps.folder",
  };

  await drive.file.create({
    fields: "id"
    resource: fileMetaData //This is where the error is, maybe it is because of Typescript but it says resource doesn't exist?
  });
};

To:

export const createFolder = async () => {
  const drive = google.drive({ version: "v3", auth: auth });
  const fileMetaData = {
    name: "Invoices",
    mimeType: "application/vnd.google-apps.folder",
  };
  const res = await drive.files
    .create({
      fields: "id",
      resource: fileMetaData,
    })
    .catch((err) => console.log(err));
  console.log(res.data);
};
  • When this modified script is run, the folder ID is returned.

Note:

  • The folder created by the service account cannot be directly seen on your Google Drive. Because the created folder is for the service account. So, when you want to see the created folder on your Google Drive with your browser, please share the folder with your Google account and change the owner of the folder from the service account to your Google account.

  • When you want to transfer the owner of the created folder from the service account to your Google account, you can achieve this by adding the following script after the folder was created by the above script. This is a sample script. By this, the created folder can be seen at the root of your Google account.

      const res = await drive.files
        .create({
          fields: "id",
          resource: fileMetaData,
        })
        .catch((err) => console.log(err));
      console.log(res.data);
    
      // Added: Transfer owner of created folder from service account to your Google account.
      const folderId = res.data.id;
      if (!folderId) return;
      const res2 = await drive.permissions
        .create({
          resource: {
            type: "user",
            role: "owner",
            emailAddress: "###",  // Please set your email address of Google account.
          },
          fileId: folderId,
          fields: "id",
          transferOwnership: true,
          moveToNewOwnersRoot: true,
        })
        .catch((err) => console.log(err));
      console.log(res2.data);
    
  • As other methods, how about the following flow?

    1. Manually create a new folder in your Google Drive of your Google account. And, please share the created folder with the email of the service account. And copy the folder ID.

    2. Create a new folder by the service account. In that case, the create folder is created to your new folder on your Google Drive. By this, you can see the created folder by the service account in your Google Drive. For this, the sample script is as follows.

       const fileMetaData = {
         name: "Invoices",
         mimeType: "application/vnd.google-apps.folder",
         parents: ["###"], // Please set the folder ID of created folder in your Google Drive.
       };
       const res = await drive.files
         .create({
           fields: "id",
           resource: fileMetaData,
         })
         .catch((err) => console.log(err));
       console.log(res.data);
      

References:

  • Related