Creates a new BoxFileStorage instance
This constructor reads the required Box authentication configuration 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 Box provider is properly configured. Returns true if client credentials or access token are present. Logs detailed error messages if configuration is incomplete.
Box supports ranged streaming via the download endpoint's Range header.
Returns the current Box API access token
This method ensures a valid token is available before returning it, refreshing or generating a new token if necessary.
A Promise that resolves to a valid access token string
Copies a file from one location to another
This method creates a copy of a file at a new location. The original file remains unchanged.
Path to the source file (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 Box storage
This method creates a folder at the specified path, automatically creating any parent folders that don't exist.
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 nested directory structure
const createResult = await storage.CreateDirectory('documents/reports/2023/Q1');
if (createResult) {
console.log('Directory created successfully');
// Now we can put files in this directory
await storage.PutObject(
'documents/reports/2023/Q1/financial-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. The URL typically expires after 60 minutes.
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 Box authentication
} catch (error) {
console.error('Error creating download URL:', error.message);
}
Creates a pre-authenticated upload URL for a file
This method creates a Box upload session and returns a URL that can be used to upload file content directly to Box without requiring 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 uploadInfo = await storage.CreatePreAuthUploadUrl('presentations/quarterly-results.pptx');
// The URL can be used to upload content directly
console.log(`Upload URL: ${uploadInfo.UploadUrl}`);
// Make sure to save the provider key, as it's needed to reference the upload
console.log(`Provider Key: ${uploadInfo.ProviderKey}`);
// You can use fetch or another HTTP client to upload to this URL
await fetch(uploadInfo.UploadUrl, {
method: 'PUT',
headers: { 'Content-Type': 'application/octet-stream' },
body: fileContent
});
} catch (error) {
console.error('Error creating upload URL:', error.message);
}
Deletes a directory from Box storage
This method deletes a folder and optionally its contents. By default, it will only delete empty folders unless recursive is set to true.
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
// Try to delete an empty folder
const deleteResult = await storage.DeleteDirectory('temp/empty-folder');
// 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 Box storage
This method permanently deletes a file or folder. It can also handle special cases like incomplete upload sessions.
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
// Delete a file
const deleteResult = await storage.DeleteObject('temp/draft-document.docx');
if (deleteResult) {
console.log('File deleted successfully or already didn\'t exist');
} else {
console.error('Failed to delete file');
}
// Delete an upload session
await storage.DeleteObject('session:1234567890:documents/large-file.zip');
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, 'application/pdf');
Gets file representation information for a Box file
This method retrieves information about available representations (such as thumbnails, previews, or other formats) for a specific file.
The Box file ID to get representations for
The representation hints string (format and options)
A Promise that resolves to a JSON object containing representations data
try {
// Get a high-resolution PNG representation of a file
const fileId = '12345';
const representations = await storage.GetFileRepresentations(
fileId,
'png?dimensions=2048x2048'
);
// Process the representation information
console.log('Available representations:', representations);
} catch (error) {
console.error('Error getting representations:', error.message);
}
Downloads a file's contents
This method retrieves the raw content of a file as a Buffer.
A Promise that resolves to a Buffer containing the file's contents
try {
// Download a text file
const fileContent = await storage.GetObject('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 about a file or folder in Box storage, such as size, type, and modification date.
A Promise that resolves to a StorageObjectMetadata object
try {
// Get metadata for a file
const metadata = await storage.GetObjectMetadata('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}`);
// Box-specific metadata is available in customMetadata
console.log(`Box ID: ${metadata.customMetadata.id}`);
} catch (error) {
console.error('Error getting metadata:', error.message);
}
Streams a file's content from Box, optionally honoring a byte range.
Uses downloads.downloadFile(fileId, { headers: { range } }), which returns a
Node.js readable stream — the file is never buffered fully in memory. The Box SDK
does not surface Content-Length/Content-Range from this call, so this method
resolves the object's total size (and content type) via GetObjectMetadata
to populate ObjectStreamResult.ContentLength / ContentRange. The supplied
inclusive Range is clamped to the object size so ContentRange.End is always valid.
Object identifier (prefer objectId) plus optional Range.
A Promise resolving to an ObjectStreamResult.
Initialize Box storage provider.
Always call this method after creating an instance.
Optionalconfig: BoxConfigOptional. 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 Box storage. 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 Box storage
This method uploads a file to the specified path in Box storage. 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 (if not provided, it will be guessed from the filename)
Optionalmetadata: Record<string, string>Optional metadata to associate with the file (not used in Box implementation)
A Promise that resolves to true if successful, false if an error occurs
// Create a simple text file
const textContent = Buffer.from('This is a sample document', 'utf8');
const uploadResult = await storage.PutObject(
'documents/sample.txt',
textContent,
'text/plain'
);
// 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,
'application/vnd.openxmlformats-officedocument.presentationml.presentation'
);
if (largeUploadResult) {
console.log('Large file uploaded successfully');
} else {
console.error('Failed to upload large file');
}
Search files in Box using Box Search API.
This method provides full-text search capabilities across file names and content using Box's native search functionality. It supports filtering by file type, date ranges, and path prefixes.
The search query string. Supports boolean operators (AND, OR, NOT) and exact phrases in quotes
Optionaloptions: FileSearchOptionsOptional search options to filter and customize results
Options for configuring a file search operation. These options allow for flexible, provider-agnostic search capabilities while still leveraging native provider search features where available.
OptionalfileTypes?: string[]File types to include in search results. Examples: ['pdf', 'docx', 'xlsx'], ['image/*'], ['text/plain'] Can use MIME types or file extensions.
OptionalmaxResults?: numberMaximum number of results to return. Defaults to 100 if not specified.
OptionalmodifiedAfter?: DateOnly return files modified after this date.
OptionalmodifiedBefore?: DateOnly return files modified before this date.
OptionalpathPrefix?: stringRestrict search to files within this path prefix. Example: 'documents/reports/' would only search within that directory.
OptionalproviderSpecific?: Record<string, unknown>Additional provider-specific search parameters. This allows providers to expose advanced features not covered by common options. Example: { 'trashed': false } for Google Drive, { 'scope': 'personal' } for SharePoint
OptionalsearchContent?: booleanWhether to search file contents in addition to names and metadata. Not all providers support content search. Defaults to false.
A Promise resolving to a FileSearchResultSet containing matching files
// Search for PDF files containing "quarterly report"
const results = await storage.SearchFiles('quarterly report', {
fileTypes: ['pdf'],
pathPrefix: 'documents/reports',
modifiedAfter: new Date('2023-01-01'),
maxResults: 50
});
console.log(`Found ${results.results.length} matching files`);
for (const file of results.results) {
console.log(`- ${file.path} (${file.size} bytes, score: ${file.relevance})`);
if (file.excerpt) {
console.log(` Excerpt: ${file.excerpt}`);
}
}
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 Box.com cloud storage
This provider allows working with files stored in Box.com. It supports authentication via access token, refresh token, or client credentials (JWT).
Remarks
This implementation requires at least one of the following authentication methods:
Access Token:
Refresh Token:
Client Credentials (JWT):
Optional configuration:
Example