In situations where storage limitations become a concern, exploring alternative solutions becomes essential. Suppose you're utilizing platforms like GitHub or Versal for hosting frontend applications, which offer restricted storage space, typically around 2GB. In such scenarios, leveraging Google Drive for storing files can be a viable option.
By integrating Google Drive with your Node.js applications, you can harness the robust storage capabilities of Google Cloud. This documentation aims to provide a concise guide on utilizing Google Drive in conjunction with Node.js to manage files efficiently.
Prerequisites
Before embarking on the integration process, ensure you have the following prerequisites in place:
- A Google account with access to the Google Cloud Console.
- Node.js installed on your local machine.
- NPM (Node Package Manager) installed.
Step 1: Set Up Google Cloud Console and Enable Google Drive API
- Go to the Google Cloud Console.
- Create a new project.
- Navigate to "APIs & Services" > "Library".
- Search for "Google Drive API" and enable it.
Step 2: Obtain Service Account Credentials
- Navigate to "APIs & Services" > "Credentials".
- Create a new Service Account.
- Download the JSON file with the credentials.
Step 3: Install Necessary Packages
Install the required packages using NPM. This includes the 'googleapis
' package, which facilitates interaction with Google APIs.
npm install googleapis
Step 4: Implement File Management Functions
Utilize the provided code snippets to implement various file management functionalities, including:
- Listing available files in Google Drive.
- Uploading files to Google Drive.
- Updating existing files in Google Drive.
- Deleting files from Google Drive.
- for that you should use folder_id and make it public and editable
Step 5: Start the project
Execute the Node.js application to perform file management operations on Google Drive. Ensure to replace placeholders such as 'FOLDER_ID_HERE' with relevant IDs and file paths. For geting folder id of drive folder we do this.
Let' Code
first we import all necessary libararies
const fs = require('fs');
const { google } = require('googleapis');
// Load API credentials from JSON file
const apikeys = require('FOLDER_ID_HERE'); // Replace 'FOLDER_ID_HERE' with the downloaded api file path
Function to authorize and get access to Google Drive API
// Define the scope for Google Drive API
const SCOPES = ['https://www.googleapis.com/auth/drive'];
// Function to authorize and get access to Google Drive API
async function authorize() {
const auth = new google.auth.JWT(
apikeys.client_email,
null,
apikeys.private_key,
SCOPES
);
try {
await auth.authorize();
return auth;
} catch (error) {
throw new Error(`Error authorizing Google Drive API: ${error.message}`);
}
}
Write a function for get all available file on that drive folder
// Function to list available files in Google Drive
async function listFiles(auth) {
const drive = google.drive({ version: 'v3', auth });
try {
const response = await drive.files.list({
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
});
const files = response.data.files;
if (files.length) {
console.log('Available files:');
files.forEach(file => {
console.log(`${file.name} (${file.id})`);
});
} else {
console.log('No files found.');
}
} catch (error) {
throw new Error(`Error listing files in Google Drive: ${error.message}`);
}
}
Write a function to upload file on drive folder
// Function to upload a file to Google Drive
async function uploadFile(auth, filePath, folderId) {
const drive = google.drive({ version: 'v3', auth });
const fileMetadata = {
name: filePath.split('/').pop(), // Extract file name from path
parents: [folderId] // Folder ID to upload the file into
};
const media = {
mimeType: 'application/octet-stream',
body: fs.createReadStream(filePath) // Readable stream for file upload
};
try {
const response = await drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id'
});
console.log('File uploaded successfully. File ID:', response.data.id);
return response.data;
} catch (error) {
throw new Error(`Error uploading file to Google Drive: ${error.message}`);
}
}
Function to delete file to folder
// Function to delete a file from Google Drive
async function deleteFile(auth, fileId) {
const drive = google.drive({ version: 'v3', auth });
try {
await drive.files.delete({
fileId: fileId
});
console.log('File deleted successfully.');
} catch (error) {
throw new Error(`Error deleting file from Google Drive: ${error.message}`);
}
}
Function to update file of drive folder
// Function to update a file in Google Drive
async function updateFile(auth, fileId, filePath) {
const drive = google.drive({ version: 'v3', auth });
const fileMetadata = {
name: filePath.split('/').pop() // Extract file name from path
};
const media = {
mimeType: 'application/octet-stream',
body: fs.createReadStream(filePath) // Readable stream for file update
};
try {
const response = await drive.files.update({
fileId: fileId,
resource: fileMetadata,
media: media
});
console.log('File updated successfully.');
} catch (error) {
throw new Error(`Error updating file in Google Drive: ${error.message}`);
}
}
How to call all function
// Main function to demonstrate file operations
async function main() {
try {
const authClient = await authorize();
// List available files
console.log('Available files:');
await listFiles(authClient);
// Upload a file
const uploadedFile = await uploadFile(authClient, 'test.txt', 'FOLDER_ID_HERE'); // Replace 'FOLDER_ID_HERE' with the desired folder ID
const fileId = uploadedFile.id;
// Update the uploaded file
await updateFile(authClient, fileId, 'updated_test.txt');
// Delete the uploaded file
await deleteFile(authClient, '1kWgn2c_yfXWDnT4DC6ZlUJEG37w79JxA');
} catch (error) {
console.error(error);
}
}
// Call the main function to start the process
main();
After doing all performance we can easily asses drive to upload folder.
Top comments (0)