Creates a new instance of GoogleDriveFileStorage.
Initializes the connection to Google Drive using either a service account key file or credentials provided directly in environment variables. Throws an error if neither authentication method is properly configured.
Protected_The ID of the FileStorageAccount this driver instance is operating for. Set during initialization via the config parameter.
Protected_The name of the FileStorageAccount (for logging/display purposes).
Protected ReadonlyproviderThe name of this storage provider, used in error messages
Gets the account ID this driver instance is operating for. Returns undefined if the driver was not initialized with an account.
Gets the account name this driver instance is operating for. Returns undefined if the driver was not initialized with an account.
Checks if Google Drive provider is properly configured. Returns true if all required OAuth credentials are present. Logs detailed error messages if configuration is incomplete.
Google Drive supports ranged streaming of regular (non-Workspace) files via the
files.get({ alt: 'media' }) endpoint with a Range header.
Copies an object within Google Drive.
This method creates a copy of a file at a new location without removing the original. It uses the Google Drive API's native file copying capabilities.
The path to the file to copy
The path where the copy should be created
A Promise resolving to a boolean indicating success
Creates a directory in Google Drive.
This method creates a folder at the specified path, creating parent folders as needed if they don't exist. Google Drive natively supports folders as a special file type with the 'application/vnd.google-apps.folder' MIME type.
The path of the directory to create
A Promise resolving to a boolean indicating success
Generates a pre-authenticated URL for downloading files from a storage provider.
This method abstracts the process of generating download URLs across different storage providers, offering a unified interface for obtaining these URLs. When called with the name of the file or object to download, it creates a URL that includes necessary authentication tokens directly in the URL, allowing for secure access without requiring additional authentication at download time.
The name of the object or file for which you want to generate a download URL. This is the name as it is known to the storage provider, and it will be used to locate the file and generate the URL.
A Promise that resolves to a string, which is the pre-authenticated download URL for the specified object or file. This URL can be used immediately for downloading the file without further authentication.
const downloadUrl = await CreatePreAuthDownloadUrl("report.pdf");
console.log(downloadUrl); // Use this URL to download your file directly
If a ProviderKey was previously returned by CreatePreAuthUploadUrl, use that as the
objectName instead of the object's natural name:
const downloadUrl = await CreatePreAuthDownloadUrl(file.ProviderKey);
console.log(downloadUrl); // Use this URL to download your file directly
This method simplifies the process of securely sharing or accessing files stored in cloud storage by providing a direct, pre-authenticated link to the file. It's particularly useful in applications where files need to be accessed or shared without navigating through the storage provider's standard authentication flow each time.
Creates a pre-authenticated upload URL for an object in Google Drive.
Google Drive doesn't directly support pre-signed upload URLs in the same way as other storage providers like S3 or Azure. Instead, uploads should be performed using the PutObject method.
The name of the object to upload
Deletes a directory and optionally its contents from Google Drive.
This method deletes a folder at the specified path. If recursive is false, it will fail if the folder has any contents. If recursive is true, it deletes the folder and all its contents.
The path of the directory to delete
If true, deletes all contents recursively (default: false)
A Promise resolving to a boolean indicating success
Deletes an object from Google Drive.
This method locates the specified file by path and deletes it from Google Drive. By default, this moves the file to the trash rather than permanently deleting it, unless your Drive settings are configured for immediate permanent deletion.
The path to the file to delete
A Promise resolving to a boolean indicating success
Checks if a directory exists in Google Drive.
This method verifies the existence of a folder at the specified path. It also checks that the item is actually a folder (has the correct MIME type), not a file with the same name.
The path of the directory to check
A Promise resolving to a boolean indicating if the directory exists
// Check if a directory exists before trying to save files to it
const exists = await driveStorage.DirectoryExists('documents/reports/');
if (!exists) {
console.log('Directory does not exist, creating it first');
await driveStorage.CreateDirectory('documents/reports/');
}
// Now safe to use the directory
await driveStorage.PutObject('documents/reports/new-report.pdf', fileData);
Downloads an object's content from Google Drive.
This method retrieves the full content of a file and returns it as a Buffer for processing in memory.
Object identifier (prefer objectId for performance, fallback to fullPath)
A Promise resolving to a Buffer containing the file's data
try {
// Fast path: Use objectId (Google Drive file ID)
const content = await driveStorage.GetObject({ objectId: '1a2b3c4d5e' });
// Slow path: Use path
const content2 = await driveStorage.GetObject({ fullPath: 'documents/config.json' });
// Parse the JSON content
const config = JSON.parse(content.toString('utf8'));
console.log('Configuration loaded:', config);
} catch (error) {
console.error('Failed to download file:', error.message);
}
Retrieves metadata for a specific object in Google Drive.
This method fetches the file information without downloading its content, which is more efficient for checking file attributes like size, type, and last modified date.
Object identifier (prefer objectId for performance, fallback to fullPath)
A Promise resolving to a StorageObjectMetadata object
try {
// Fast path: Use objectId (Google Drive file ID)
const metadata = await driveStorage.GetObjectMetadata({ objectId: '1a2b3c4d5e' });
// Slow path: Use path
const metadata2 = await driveStorage.GetObjectMetadata({ fullPath: 'documents/report.pdf' });
console.log(`File: ${metadata.name}`);
console.log(`Size: ${metadata.size} bytes`);
console.log(`Last modified: ${metadata.lastModified}`);
} catch (error) {
console.error('File does not exist or cannot be accessed');
}
Streams a file's content from Google Drive, optionally honoring a byte range.
Uses files.get({ fileId, alt: 'media' }, { responseType: 'stream', headers: { Range } }),
which returns a Node.js readable stream — the file is never buffered fully in memory. The
Drive media endpoint honors the HTTP Range header, so the inclusive Range is encoded via
the shared BuildHttpRangeHeader. The streamed response doesn't reliably surface the
total object size, so this method resolves size/content-type via GetObjectMetadata
(mirroring the Box driver) and clamps the range to the object size.
Google Workspace files (Docs/Sheets/Slides/Drawings) are not directly downloadable — they must be exported to a concrete format, which has no Range semantics — so streaming throws for those types. Callers should fall back to GetObject (which performs the export).
Object identifier (prefer objectId) plus optional Range.
A Promise resolving to an ObjectStreamResult.
Initialize Google Drive storage provider.
Always call this method after creating an instance.
Optionalconfig: GoogleDriveConfigOptional. Omit to use env vars, provide to override with database creds.
Lists objects in a directory in Google Drive.
This method retrieves all files and folders directly inside the specified folder path. It handles Google Drive's native folder structure and converts the Drive API responses to the standardized StorageListResult format.
The path to the directory to list
Delimiter character (unused in Google Drive implementation)
A Promise resolving to a StorageListResult containing objects and prefixes
// List all files and directories in the documents folder
const result = await driveStorage.ListObjects('documents/');
// Process files
for (const file of result.objects) {
console.log(`File: ${file.name}, Size: ${file.size}, Type: ${file.contentType}`);
}
// Process subdirectories
for (const dir of result.prefixes) {
console.log(`Directory: ${dir}`);
}
Moves an object from one location to another within Google Drive.
This method first locates the file to be moved, then gets or creates the destination folder, and finally updates the file's name and parent folder. Google Drive has native support for moving files between folders.
The current path of the object
The new path for the object
A Promise resolving to a boolean indicating success
Checks if an object exists in Google Drive.
This method verifies the existence of a file at the specified path without downloading its content.
The path to the file to check
A Promise resolving to a boolean indicating if the file exists
// Check if a file exists before attempting to use it
const exists = await driveStorage.ObjectExists('documents/report.pdf');
if (exists) {
console.log('File exists, proceeding with download');
const content = await driveStorage.GetObject('documents/report.pdf');
// Process the content...
} else {
console.log('File does not exist');
}
Uploads data to an object in Google Drive.
This method directly uploads a Buffer of data to a file with the specified path. It will create any necessary parent folders if they don't exist, and will update the file if it already exists or create a new one if it doesn't.
The path to the file to upload
The Buffer containing the data to upload
OptionalcontentType: stringOptional MIME type for the file (inferred from name if not provided)
Optionalmetadata: Record<string, string>Optional key-value pairs of custom metadata (not supported in current implementation)
A Promise resolving to a boolean indicating success
Searches for files in Google Drive using the Drive API search capabilities.
Google Drive search syntax supports:
Content search is always enabled for supported file types (Docs, Sheets, PDFs, etc.) when searchContent option is true.
Search query using Google Drive search syntax
Optionaloptions: FileSearchOptionsSearch options
Promise resolving to search results
// Simple name search
const results = await storage.SearchFiles('quarterly report');
// Search with file type filter
const pdfResults = await storage.SearchFiles('budget', {
fileTypes: ['pdf'],
modifiedAfter: new Date('2024-01-01')
});
// Content search
const contentResults = await storage.SearchFiles('machine learning', {
searchContent: true,
pathPrefix: 'documents/research/'
});
ProtectedthrowHelper method to throw an UnsupportedOperationError with appropriate context. This method simplifies implementation of methods not supported by specific providers.
The name of the method that is not supported
Google Drive implementation of the FileStorageBase interface.
This class provides methods for interacting with Google Drive as a file storage provider. It implements most of the abstract methods defined in FileStorageBase and handles Google Drive-specific authentication, authorization, and file operations.
Unlike other storage providers like S3 or Azure, Google Drive has native concepts of folders and files with hierarchical paths, which makes some operations more natural while others (like pre-authenticated upload URLs) are not directly supported.
It requires one of the following environment variables to be set:
Optionally, you can set:
Example