Creates a new BoxFileStorage instance
This constructor reads the required Box authentication configuration from environment variables.
Error if refresh token is provided without client ID and secret
Private _accessBox API access token
Private _baseBase URL for Box API
Private _clientBox SDK client for making API calls
Private _clientBox application client ID
Private _clientBox application client secret
Private _enterpriseBox enterprise ID for JWT auth
Private _refreshBox API refresh token
Private _rootID of the Box folder to use as root
Private _tokenTimestamp when current access token expires
Private _uploadBase URL for Box Upload API
Protected Readonly providerThe name of this storage provider
Checks if Box provider is properly configured. Returns true if client credentials are present.
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
// Get a valid Box access token
const token = await storage.AccessToken();
console.log(`Using access token: ${token}`);
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
// Copy a template file to a new location with a different name
const copyResult = await storage.CopyObject(
'templates/financial-report.xlsx',
'reports/2023/q1-financial-report.xlsx'
);
if (copyResult) {
console.log('File copied successfully');
} else {
console.error('Failed to copy file');
}
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
Error if the file doesn't exist or URL creation fails
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
Error if the URL creation fails
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
Error if the request fails
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
Error if the file doesn't exist or cannot be downloaded
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
Error if the object doesn't exist or cannot be accessed
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);
}
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
// Move a file to a different folder and rename it
const moveResult = await storage.MoveObject(
'documents/old-report.pdf',
'archive/2023/annual-report.pdf'
);
if (moveResult) {
console.log('File moved successfully');
} else {
console.error('Failed to move file');
}
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
Optional contentType: stringOptional MIME type of the file (if not provided, it will be guessed from the filename)
Optional metadata: 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
Optional options: FileSearchOptionsOptional search options to filter and customize results
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}`);
}
}
Private _buildPrivate Builds a list of file extensions from file type specifications
This helper method converts generic file type specifications (extensions or MIME types) into Box API fileExtensions parameter values.
Array of file extensions (e.g., 'pdf', 'docx') or MIME types
Array of file extension strings (without dots)
Private _convertPrivate Converts a Box API item to StorageObjectMetadata
This helper method transforms a Box API item representation into the standard StorageObjectMetadata format used by FileStorageBase.
The Box API item object
The parent path string
A StorageObjectMetadata object
Private _findPrivate Finds a Box folder ID by traversing a path string
This helper method navigates through the Box folder hierarchy, following each segment of the path to find the ID of the target folder. It uses pagination to handle large folders efficiently.
The path string to resolve (e.g., 'documents/reports/2023')
A Promise that resolves to the Box folder ID
Error if any segment of the path cannot be found
Private _getPrivate Obtains an access token using client credentials flow
This method requests a new access token using the Box client credentials flow (JWT) with the enterprise as the subject.
A Promise that resolves with the access token
Error if token acquisition fails
Private _getPrivate Resolves a path string to a Box item ID
This helper method navigates the Box folder hierarchy to find the item at the specified path, returning its Box ID.
The path to resolve
A Promise that resolves to the Box item ID
Error if the item does not exist
Private _getPrivate _isPrivate _parsePrivate Parses a path string into Box API components
This helper method converts a standard path string (e.g., 'documents/reports/file.txt') into components used by the Box API (folder ID, name, parent path).
The path to parse
An object containing the parsed components: id, name, and parent
Private _reconstructPrivate Reconstructs the full path to a Box item from its pathCollection
This helper method builds the complete path by traversing the parent folder hierarchy stored in the item's pathCollection.
The Box item with pathCollection data
The full path string (e.g., 'documents/reports/file.pdf')
Private _refreshInitializes the Box storage driver
This method must be called after creating a BoxFileStorage instance. It initializes the Box SDK and creates the client for API calls.
A Promise that resolves when initialization is complete
const storage = new BoxFileStorage();
await storage.initialize();
// Now the storage provider is ready to use
Protected throwHelper 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
UnsupportedOperationError with information about the unsupported method and provider
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