Creates a new DropboxFileStorage instance
This constructor initializes the Dropbox client using the provided credentials from environment variables.
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
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 Dropbox provider is properly configured. Returns true if access token is present. Logs detailed error messages if configuration is incomplete.
Dropbox supports ranged streaming: filesGetTemporaryLink returns a short-lived
pre-authenticated content URL that honors the HTTP Range header.
Copies a file or folder from one location to another
This method creates a copy of a file or folder at a new location. The original file or folder remains unchanged.
Path to the source object (e.g., 'templates/report-template.docx')
Path where the copy should be created (e.g., 'documents/new-report.docx')
A Promise that resolves to true if successful, false if an error occurs
Creates a new directory (folder) in Dropbox
This method creates a folder at the specified path.
Path where the directory should be created (e.g., 'documents/reports/2023')
A Promise that resolves to true if successful, false if an error occurs
// Create a new folder
const createResult = await storage.CreateDirectory('documents/reports/2023');
if (createResult) {
console.log('Directory created successfully');
// Now we can put files in this directory
await storage.PutObject(
'documents/reports/2023/annual-summary.xlsx',
fileContent,
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
);
} else {
console.error('Failed to create directory');
}
Creates a pre-authenticated download URL for a file
This method generates a time-limited URL that can be used to download a file without authentication.
Path to the file to download (e.g., 'documents/report.pdf')
A Promise that resolves to the download URL string
try {
// Generate a pre-authenticated download URL
const downloadUrl = await storage.CreatePreAuthDownloadUrl('documents/financial-report.pdf');
console.log(`Download the file using this URL: ${downloadUrl}`);
// The URL can be shared or used in a browser to download the file
// without requiring Dropbox authentication
} catch (error) {
console.error('Error creating download URL:', error.message);
}
Creates a pre-authenticated upload URL for a file
This method generates a time-limited URL that can be used to upload a file directly to Dropbox without additional authentication.
Path where the file should be uploaded (e.g., 'documents/report.pdf')
A Promise that resolves to an object containing the upload URL and provider key
try {
// Generate a pre-authenticated upload URL
const uploadPayload = await storage.CreatePreAuthUploadUrl('documents/financial-report.pdf');
console.log(`Upload the file to this URL: ${uploadPayload.UploadUrl}`);
// Use the URL to upload file directly from client
// POST request with Content-Type: application/octet-stream
} catch (error) {
console.error('Error creating upload URL:', error.message);
}
Deletes a directory from Dropbox
This method deletes a folder and optionally ensures it's empty first. Note that Dropbox API always deletes folders recursively, so we perform an additional check when recursive=false to protect against accidental deletion.
Path to the directory to delete (e.g., 'documents/old-reports')
If true, delete the directory and all its contents; if false, only delete if empty
A Promise that resolves to true if successful, false if an error occurs
// Attempt to delete an empty folder
const deleteResult = await storage.DeleteDirectory('temp/empty-folder', false);
// Delete a folder and all its contents
const recursiveDeleteResult = await storage.DeleteDirectory('archive/old-data', true);
if (recursiveDeleteResult) {
console.log('Folder and all its contents deleted successfully');
} else {
console.error('Failed to delete folder');
}
Deletes a file or folder from Dropbox
This method permanently deletes a file or folder from Dropbox storage.
Path to the object to delete (e.g., 'documents/old-report.docx')
A Promise that resolves to true if successful, false if an error occurs
Checks if a directory exists
This method verifies whether a folder exists at the specified path. Unlike ObjectExists, this method also checks that the item is a folder.
Path to check (e.g., 'documents/reports')
A Promise that resolves to true if the directory exists, false otherwise
// Check if a directory exists before creating a file in it
const dirExists = await storage.DirectoryExists('documents/reports');
if (!dirExists) {
// Create the directory first
await storage.CreateDirectory('documents/reports');
}
// Now we can safely put a file in this directory
await storage.PutObject('documents/reports/annual-summary.pdf', fileContent);
Downloads a file's contents
This method retrieves the raw content of a file as a Buffer.
Object identifier (prefer objectId for performance, fallback to fullPath)
A Promise that resolves to a Buffer containing the file's contents
try {
// Fast path: Use objectId (Dropbox file ID)
const fileContent = await storage.GetObject({ objectId: 'id:a4ayc_80_OEAAAAAAAAAXw' });
// Slow path: Use path
const fileContent2 = await storage.GetObject({ fullPath: 'documents/notes.txt' });
// Convert Buffer to string for text files
const textContent = fileContent.toString('utf8');
console.log('File content:', textContent);
// For binary files, you can write the buffer to disk
// or process it as needed
} catch (error) {
console.error('Error downloading file:', error.message);
}
Gets metadata for a file or folder
This method retrieves metadata information about a file or folder, such as its name, size, content type, and last modified date.
Object identifier (prefer objectId for performance, fallback to fullPath)
A Promise that resolves to a StorageObjectMetadata object
try {
// Fast path: Use objectId (Dropbox file ID)
const metadata = await storage.GetObjectMetadata({ objectId: 'id:a4ayc_80_OEAAAAAAAAAXw' });
// Slow path: Use path
const metadata2 = await storage.GetObjectMetadata({ fullPath: 'presentations/quarterly-update.pptx' });
console.log(`Name: ${metadata.name}`);
console.log(`Path: ${metadata.path}`);
console.log(`Size: ${metadata.size} bytes`);
console.log(`Content Type: ${metadata.contentType}`);
console.log(`Last Modified: ${metadata.lastModified}`);
console.log(`Is Directory: ${metadata.isDirectory}`);
// Dropbox-specific metadata is available in customMetadata
console.log(`Dropbox ID: ${metadata.customMetadata.id}`);
console.log(`Revision: ${metadata.customMetadata.rev}`);
} catch (error) {
console.error('Error getting metadata:', error.message);
}
Streams a file's content from Dropbox, optionally honoring a byte range.
The Dropbox SDK's filesDownload returns the entire file binary in memory and exposes no
Range seam, so this method instead requests a short-lived temporary content link via
filesGetTemporaryLink and fetches it with the inclusive Range encoded by
BuildHttpRangeHeader. The Dropbox content endpoint honors the Range header. The fetch
response body is a web ReadableStream, converted to a Node Readable via
Readable.fromWeb so the file is never fully buffered. Content-Type/Content-Length/
Content-Range are read off the HTTP response headers; the total object size falls back to the
link's metadata.size when the server omits Content-Range.
Object identifier (prefer objectId) plus optional Range.
A Promise resolving to an ObjectStreamResult.
Initialize Dropbox storage provider.
Always call this method after creating an instance.
Optionalconfig: DropboxConfigOptional. Omit to use env vars, provide to override with database creds.
Lists files and folders in a given directory
This method retrieves all files and subfolders in the specified directory. It returns both a list of object metadata and a list of directory prefixes.
Path to the directory to list (e.g., 'documents/reports')
Optional delimiter character (default: '/')
A Promise that resolves to a StorageListResult containing objects and prefixes
objects array includes both files and foldersprefixes array includes only folder paths (with trailing slashes)// List all files and folders in the 'documents' directory
const result = await storage.ListObjects('documents');
// Process files and folders
console.log(`Found ${result.objects.length} items:`);
for (const obj of result.objects) {
console.log(`- ${obj.name} (${obj.isDirectory ? 'Folder' : 'File'}, ${obj.size} bytes)`);
}
// List subfolders only
console.log(`Found ${result.prefixes.length} subfolders:`);
for (const prefix of result.prefixes) {
console.log(`- ${prefix}`);
}
Moves a file or folder from one location to another
This method moves a file or folder to a new location in Dropbox. It handles both renaming and changing the parent folder.
Current path of the object (e.g., 'old-folder/document.docx')
New path for the object (e.g., 'new-folder/renamed-document.docx')
A Promise that resolves to true if successful, false otherwise
Checks if a file or folder exists
This method verifies whether an object (file or folder) exists at the specified path.
Path to check (e.g., 'documents/report.pdf')
A Promise that resolves to true if the object exists, false otherwise
// Check if a file exists before attempting to download it
const exists = await storage.ObjectExists('presentations/quarterly-update.pptx');
if (exists) {
// File exists, proceed with download
const fileContent = await storage.GetObject('presentations/quarterly-update.pptx');
// Process the file...
} else {
console.log('File does not exist');
}
Uploads a file to Dropbox
This method uploads a file to the specified path in Dropbox. It automatically determines whether to use a simple upload or chunked upload based on file size.
Path where the file should be uploaded (e.g., 'documents/report.pdf')
Buffer containing the file content
OptionalcontentType: stringOptional MIME type of the file (not used in Dropbox implementation)
Optionalmetadata: Record<string, string>Optional metadata to associate with the file (not used in Dropbox implementation)
A Promise that resolves to true if successful, false if an error occurs
// Upload a simple text file
const textContent = Buffer.from('This is a sample document', 'utf8');
const uploadResult = await storage.PutObject('documents/sample.txt', textContent);
// Upload a large file using chunked upload
const largeFileBuffer = fs.readFileSync('/path/to/large-presentation.pptx');
const largeUploadResult = await storage.PutObject(
'presentations/quarterly-results.pptx',
largeFileBuffer
);
if (largeUploadResult) {
console.log('Large file uploaded successfully');
} else {
console.error('Failed to upload large file');
}
Search files in Dropbox using Dropbox Search API v2.
Dropbox provides full-text search capabilities across file names and content. The search API supports natural language queries and can search both filenames and file content based on the searchContent option.
The search query string (supports natural language and quoted phrases)
Optionaloptions: FileSearchOptionsSearch options for filtering and limiting results
A Promise resolving to search results
// Simple filename 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 within a specific folder
const contentResults = await storage.SearchFiles('machine learning', {
searchContent: true,
pathPrefix: 'documents/research',
maxResults: 50
});
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
FileStorageBase implementation for Dropbox cloud storage
This provider allows working with files stored in Dropbox. It supports authentication via access token or refresh token with app credentials.
Remarks
This implementation requires one of the following authentication methods:
Access Token:
Refresh Token:
Optional configuration:
Example