Hey there, fellow dev! Ready to supercharge your app with Google Drive integration? You're in the right place. We'll be using the googleapis
package to make this happen, so buckle up and let's dive in!
Before we start, make sure you've got:
First things first, let's get our project set up in Google Cloud Console:
Trust me, this part's crucial. Take your time here, and you'll thank yourself later.
Now, let's get our hands dirty with some code:
npm init -y npm install googleapis
Create an index.js
file, and we're ready to roll!
Authentication is where the magic happens. We'll implement the OAuth 2.0 flow:
const { google } = require('googleapis'); const oauth2Client = new google.auth.OAuth2( YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, YOUR_REDIRECT_URL ); // Generate a url that asks permissions for Google Drive scope const scopes = ['https://www.googleapis.com/auth/drive']; const url = oauth2Client.generateAuthUrl({ access_type: 'offline', scope: scopes }); // Handle the OAuth 2.0 server response
Don't forget to securely store and manage your tokens!
Now for the fun part - let's interact with Google Drive:
const drive = google.drive({ version: 'v3', auth: oauth2Client }); async function listFiles() { const res = await drive.files.list({ pageSize: 10, fields: 'nextPageToken, files(id, name)', }); console.log(res.data.files); }
async function uploadFile(filePath) { const res = await drive.files.create({ requestBody: { name: 'test.jpg', mimeType: 'image/jpeg', }, media: { mimeType: 'image/jpeg', body: fs.createReadStream(filePath), }, }); console.log('File Id:', res.data.id); }
async function downloadFile(fileId, destPath) { const res = await drive.files.get({fileId: fileId, alt: 'media'}, {responseType: 'stream'}); res.data .on('end', () => console.log('Done downloading file.')) .on('error', err => console.error('Error downloading file.', err)) .pipe(fs.createWriteStream(destPath)); }
Want to level up? Try these:
Remember, things can go wrong. Always wrap your API calls in try/catch blocks and handle rate limiting gracefully. Your future self will thank you!
When things get tricky, the Google OAuth 2.0 Playground is your best friend. And don't be shy with those console.log
statements - they're lifesavers!
And there you have it! You're now equipped to integrate Google Drive into your JS projects like a pro. Remember, the official documentation is always there if you need it.
Now go forth and build something awesome! 🚀