gdrive-link
v1.0.3
Published
A simple library to use Google Drive as a storage backend with personal accounts.
Downloads
486
Maintainers
Readme
🚀 gdrive-link
Turn your Personal Google Drive into a high-capacity, reliable object storage backend.
A lightweight Node.js library that allows you to use your personal Google Drive (with its generous 15GB free storage or up to 15TB+ with Google One) as a storage backend for your applications. Think of it as a simplified, "bucket-based" alternative to AWS S3 or Google Cloud Storage, optimized for developers who want to skip the complexity and costs of enterprise storage.
✨ Features
- Personal Account Storage: Leverage your existing Google Drive quota (15GB free, or much more if you have a Google One subscription).
- Interactive CLI: Built-in
authandhealthcommands for zero-code setup. - Bucket-like API: Familiar
upload,download,list,delete,move, andcopymethods. - Streams & Buffers: Seamlessly handle large files with Node.js Streams or simple Buffers.
- Auto-Refresh Tokens: The library automatically handles OAuth2 token refreshing and token persistence.
- Storage Monitoring: Programmatically check your remaining storage quota and usage.
- Health Diagnostics: Verify your connection and token validity with a single command.
🛠️ Installation
npm install gdrive-link🔑 Google Cloud Setup
Before using gdrive-link, you need to create a project in the Google Cloud Console and generate an OAuth client ID.
- Create Project: Go to the Google Cloud Console and create a new project.
- Enable API: Search for "Google Drive API" and click Enable.
- Configure Consent Screen:
- Go to APIs & Services > OAuth consent screen.
- Choose User Type: External.
- Fill in the required fields (App name, support email, etc.).
- In Scopes, add
.../auth/drive(or.../auth/drive.filefor limited access). - Crucial: Add your own email to Test users.
- Create Credentials:
- Go to APIs & Services > Credentials.
- Click Create Credentials > OAuth client ID.
- Select Application type: Desktop App.
- Name it (e.g., "gdrive-link-app") and click Create.
- Download JSON: Click the Download icon next to your new client ID to get the
oauth_client.jsonfile.
⚡ Quickstart (CLI)
Place your oauth_client.json in your project's root folder.
1. Authenticate
Generate your initial token.json without writing a single line of code:
npx gdrive-link authFollow the link, sign in, and you're done! Your token.json is saved automatically.
2. Verify Connection
Check if your credentials are valid and which account is connected:
npx gdrive-link health📖 Programmatic Usage
Initialization
import DriveStorage from 'gdrive-link';
const storage = new DriveStorage({
credentials: './oauth_client.json', // Path OR parsed object
token: './token.json', // Path OR parsed object
rootFolderId: 'FOLDER_ID_HERE', // (Optional) ID of the folder to use as root
tokenPath: './token.json' // (Optional) Path to auto-save refreshed tokens
});File Operations
Upload a File (Buffer)
const buffer = fs.readFileSync('photo.jpg');
const file = await storage.upload('my-bucket', 'photo.jpg', buffer, 'image/jpeg');
console.log(`Uploaded ID: ${file.id}`);Upload a File (Stream)
const stream = fs.createReadStream('large-video.mp4');
await storage.upload('videos', 'intro.mp4', stream, 'video/mp4');Download a File (Buffer)
const data = await storage.download('my-bucket', 'photo.jpg');
fs.writeFileSync('restored.jpg', data);Download a File (Readable Stream)
const stream = await storage.downloadStream('my-bucket', 'photo.jpg');
stream.pipe(fs.createWriteStream('streamed_photo.jpg'));Management Operations
List Files in a Bucket
const files = await storage.list('my-bucket');
files.forEach(f => console.log(`${f.name} (${f.size} bytes)`));Delete a File
await storage.delete('my-bucket', 'obsolete.txt');Check Your Usage & Quota
const usage = await storage.usage();
console.log(`Disk Space: ${usage.used_gb} GB used of ${usage.total_gb} GB (${usage.percent_used})`);🧪 API Reference
DriveStorage Class
| Option | Type | Description |
| :--- | :--- | :--- |
| credentials | string \| object | Path to oauth_client.json or the parsed content. |
| token | string \| object | Path to token.json or the parsed content. |
| tokenPath | string | (Optional) File path to automatically save refreshed tokens. |
| rootFolderId | string | (Optional) Use a specific Drive folder as the root for all "buckets". |
Methods
async upload(bucket, filename, data, mimeType): Uploads data (Buffer or Stream) to a specific bucket. Replaces if the file already exists.async download(bucket, filename): Returns the file content as a Buffer.async downloadStream(bucket, filename): Returns the file content as a Readable Stream.async list(bucket): Lists all files within a bucket.async delete(bucket, filename): Deletes a specific file from a bucket.async exists(bucket, filename): Checks if a file exists. Returns a boolean.async move(srcBucket, filename, destBucket): Moves a file between buckets.async copy(bucket, filename, newFilename): Creates a copy of a file within the same bucket.async usage(): Returns detailed storage quota information (GB, MB, Percentage).async checkHealth(): Returns connection status, user email, and token expiry details.
🛡️ Security Best Practices
[!CAUTION] NEVER commit
oauth_client.jsonortoken.jsonto public repositories (like GitHub). Add them to your.gitignoreimmediately.
- Limited Scopes: In the Google Cloud Console, you can limit the scope to
https://www.googleapis.com/auth/drive.file. This will only allow the app to access files it has created itself, offering better security. - Token Persistence: If you are deploying to a serverless environment (like Vercel or AWS Lambda), pass the
tokenandcredentialsas objects from environment variables instead of local file paths.
❓ FAQ & Troubleshooting
"Redirect URI Mismatch" Error
Ensure your OAuth Client is a Desktop App. If you used "Web App", you must add http://localhost:3000 to the Authorized Redirect URIs in the Google Cloud Console.
"Insufficient Permissions"
Make sure you enabled the Google Drive API (not just the Picker API) and that your OAuth screen is configured with the correct scopes.
"Token is expired"
The library handles refreshment automatically if you have a refresh_token in your token.json. If you don't, re-run npx gdrive-link auth and ensure you see a "Consent" screen.
💬 Support & Community
Join our Discord for help, suggestions, or to showcase what you've built:
📜 License
MIT © 2024
