This tutorial explains how you can connect to Google Drive or any other Google API from a service account without user authentication.
This step-by-step guide will guide you on how to upload files to Google Drive with a service account Node.js
, For this example, we have a folder on your local hard drive that contains many files and we need to upload these files to a specific folder in Google Drive.
1. Create a Google Cloud Project
go for cloud.google.com
And create a new Google Cloud Project. Give your project a name, change the project id and click Create
switch.
2. Enable Google API
choosing APIs & Services
Click on More from the left menu Enable APIs and Services
To enable various Google APIs. If you plan to upload files to Google Drive then you need to enable Drive API. If you want to use Google Cloud Storage API you need to enable Storage API.
3. Create a Service Account
in APIs & Services
section, click on Credentials
and click Create credentials
To create a service account.
3a. describe service account
Give your service account a name and a service account ID. This is like an email address and will be used to identify your service account in the future. Click Done
To finish creating a service account.
3b. create a key file
In the Cloud Console, go to the IAM & Admin > Service Accounts page. Click the email address of the service account for which you want to create a key. press Keys
tab. press Add key
drop-down menu, then select Create new key
,
choosing JSON
as the key type and then click Create. This will download a JSON file containing your private key. Do not commit this file to Github repository.
4. Share a Drive Folder
For this example, we are looking to upload files from a local folder to a specific folder in Google Drive.
Go to your Google Drive and create a new folder. Right-click the folder, choose Share, and add the email address of the service account you created in Step 3 as an editor to this folder.
This way your Node.js application will be able to access this folder and upload files to it. The application will not have access to any other resources on your Google Drive.
5. Configure Node.js App
Now that the service account is setup, we need to setup a Node.js app that will upload files to Google Drive. We will run this app from the command line but you can also convert it into a web app with Google Cloud Run and Docker.
5a. Create an Authorized OAuth2 Client
To change service.json
Your service account key with the name of the file that you created in step 3b.
const { google } = require('googleapis');
const path = require('path');
const getDriveService = () => {
const KEYFILEPATH = path.join(__dirname, 'service.json');
const SCOPES = ['https://www.googleapis.com/auth/drive'];
const auth = new google.auth.GoogleAuth({
keyFile: KEYFILEPATH,
scopes: SCOPES,
});
const driveService = google.drive({ version: 'v3', auth });
return driveService;
};
module.exports = getDriveService;
5b. write file uploader
Replace the parent folder with the folder ID of the Google Drive folder you want to upload to. After the file is uploaded, we will also move the local file to the Trash.
const fs = require('fs');
const getInvoiceFolder = require('./folder');
const drive = require('./service');
const uploadSingleFile = async (fileName, filePath) => {
const folderId = 'DRIVE_FOLDER_ID';
const { data: { id, name } = {} } = await drive.files.create({
resource: {
name: fileName,
parents: [folderId],
},
media: {
mimeType: 'application/pdf',
body: fs.createReadStream(filePath),
},
fields: 'id,name',
});
console.log('File Uploaded', name, id);
};
const scanFolderForFiles = async (folderPath) => {
const folder = await fs.promises.opendir(folderPath);
for await (const dirent of folder) {
if (dirent.isFile() && dirent.name.endsWith('.pdf')) {
await uploadSingleFile(dirent.name, path.join(folderPath, dirent.name));
await fs.promises.rm(filePath);
}
}
};
module.exports = scanFolderForFiles;
6. Run File Uploader
Now that everything is setup, create a index.js
file and run node index.js
Command to upload files to Google Drive.
const scanFolderForFiles = require('./scan');
scanFolderForFiles('local-folder').then(() => {
console.log('🔥 All files have been uploaded to Google Drive successfully!');
});
you can consider using
https://www.googleapis.com/auth/drive.file
scope instead of too widehttps://www.googleapis.com/auth/drive
scope. In that case, the initial parent folder must also be created with the same app otherwise it will not have permission to write to the folder.
Leave a Review