### Uploading Large Files Example - JavaScript Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md Demonstrates the process of uploading large files by splitting them into parts. It covers initiating the upload, getting upload URLs, uploading individual parts, and finishing the upload. It also shows how to list parts to handle interrupted uploads. ```javascript let response = await b2.startLargeFile({ bucketId, fileName }); let fileId = response.data.fileId; let response = await b2.getUploadPartUrl({ fileId }); let uploadURL = response.data.uploadUrl; let authToken = response.data.authorizationToken; response = await b2.uploadPart({ partNumber: parNum, uploadUrl: uploadURL, uploadAuthToken: authToken, data: buf }); // status checks etc. let response = await b2.finishLargeFile({ fileId, partSha1Array: parts.map(buf => sha1(buf)) }); let response = await b2.listParts({ fileId, startPartNumber: 0, maxPartCount: 1000 }); ``` -------------------------------- ### Start Large File Upload - JavaScript Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md Initiates a large file upload process by providing the bucket ID and file name. This function returns a promise that resolves with the file ID necessary for subsequent part uploads. ```javascript b2.startLargeFile({ bucketId: 'bucketId', fileName: 'fileName' // ...common arguments (optional) }); // returns promise ``` -------------------------------- ### Get Bucket Information using Backblaze B2 Client (Node.js) Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md Shows how to retrieve information about a specific Backblaze B2 bucket after successful authorization. This function uses async/await for cleaner promise handling. ```javascript const B2 = require('backblaze-b2'); const b2 = new B2({ applicationKeyId: 'applicationKeyId', applicationKey: 'applicationKey' }); async function GetBucket() { try { await b2.authorize(); let response = await b2.getBucket({ bucketName: 'my-bucket' }); console.log(response.data); } catch (err) { console.log('Error getting bucket:', err); } } ``` -------------------------------- ### Get Download Authorization - JavaScript Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Generates a temporary authorization token for downloading files from a private bucket. Requires bucket ID, file name prefix, and duration. Returns an authorization token, bucket ID, and file name prefix. ```javascript async function getDownloadAuthorization() { await b2.authorize(); try { const response = await b2.getDownloadAuthorization({ bucketId: '4a48fe8875c6214145260818', fileNamePrefix: 'documents/', validDurationInSeconds: 3600, // 1 hour b2ContentDisposition: 'attachment; filename="report.pdf"' }); console.log('Download auth:', { authorizationToken: response.data.authorizationToken, bucketId: response.data.bucketId, fileNamePrefix: response.data.fileNamePrefix }); // Use token in URL: https://f001.backblazeb2.com/file/bucket/path?Authorization=TOKEN } catch (err) { console.error('Get download auth failed:', err.response?.data || err.message); } } ``` -------------------------------- ### Get Bucket API Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Retrieves information about a specific bucket using its name or ID. This is particularly useful when working with restricted application keys. ```APIDOC ## POST /b2api/v2/b2_list_buckets ### Description Retrieves information about a specific bucket by name or ID. Useful when working with restricted application keys that cannot list all buckets. ### Method POST ### Endpoint /b2api/v2/b2_list_buckets ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **bucketName** (string) - Optional - The name of the bucket to retrieve. - **bucketId** (string) - Optional - The ID of the bucket to retrieve. Use either `bucketName` or `bucketId`. ### Request Example ```javascript async function getBucket() { await b2.authorize(); try { const response = await b2.getBucket({ bucketName: 'my-bucket' // Or use bucketId: '4a48fe8875c6214145260818' }); const bucket = response.data.buckets[0]; console.log('Bucket info:', { bucketId: bucket.bucketId, bucketName: bucket.bucketName, revision: bucket.revision }); } catch (err) { console.error('Get bucket failed:', err.response?.data || err.message); } } ``` ### Response #### Success Response (200) - **buckets** (array) - An array containing the matching bucket object. - **bucketId** (string) - The unique identifier for the bucket. - **bucketName** (string) - The name of the bucket. - **revision** (integer) - The revision number of the bucket. #### Response Example ```json { "buckets": [ { "bucketId": "4a48fe8875c6214145260818", "bucketName": "my-bucket", "revision": 2 } ] } ``` ``` -------------------------------- ### List API Keys - JavaScript Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md Retrieves a list of Backblaze B2 API keys associated with the account. Supports pagination by specifying the maximum number of keys to return and a starting key ID from a previous response. ```javascript b2.listKeys({ maxKeyCount: 10, // limit number of keys returned (optional) startApplicationKeyId: '...', // use `nextApplicationKeyId` from previous response when `maxKeyCount` is set (optional) // ...common arguments (optional) }); // returns promise ``` -------------------------------- ### Get Upload Part URL - JavaScript Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md Retrieves a URL and authorization token required for uploading parts of a large file. This URL is valid for 24 hours or until an upload part fails. ```javascript b2.getUploadPartUrl({ fileId: 'fileId' // ...common arguments (optional) }); // returns promise ``` -------------------------------- ### Get Backblaze B2 Bucket Information Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Fetches details for a specific bucket using its name or ID. This is particularly useful when working with restricted application keys that cannot list all buckets. ```javascript async function getBucket() { await b2.authorize(); try { const response = await b2.getBucket({ bucketName: 'my-bucket' // Or use bucketId: '4a48fe8875c6214145260818' }); const bucket = response.data.buckets[0]; console.log('Bucket info:', { bucketId: bucket.bucketId, bucketName: bucket.bucketName, revision: bucket.revision }); // Output: { bucketId: '4a48fe8875c6214145260818', bucketName: 'my-bucket', revision: 2 } } catch (err) { console.error('Get bucket failed:', err.response?.data || err.message); } } ``` -------------------------------- ### Backblaze B2 File Upload Operations Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md JavaScript functions for uploading files to Backblaze B2. This includes getting the upload URL, uploading files (including large ones), and monitoring upload progress. Files can be uploaded as Buffers with optional metadata and content type. ```javascript // Get upload URL b2.getUploadUrl({ bucketId: 'bucketId' // ...common_args }); // Upload a file b2.uploadFile({ uploadUrl: 'uploadUrl', uploadAuthToken: 'uploadAuthToken', fileName: 'fileName', contentLength: 0, // optional mime: '', // optional data: 'data', // expects a Buffer hash: 'sha1-hash', // optional info: { key1: 'value' }, // optional info headers onUploadProgress: (event) => {} // ...common_args }); // Start large file upload (functionality not fully detailed in snippet) // b2.startLargeFile({...}); ``` -------------------------------- ### Get File Information by File ID in Backblaze B2 Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Retrieves metadata for a specific file in Backblaze B2 using its unique file ID. Includes details like file name, content type, size, SHA1 hash, custom info headers, and upload timestamp. Requires authorization. ```javascript async function getFileInfo() { await b2.authorize(); try { const response = await b2.getFileInfo({ fileId: '4_z4a48fe8875c6214145260818_f1190...' }); console.log('File info:', { fileName: response.data.fileName, contentType: response.data.contentType, contentLength: response.data.contentLength, contentSha1: response.data.contentSha1, fileInfo: response.data.fileInfo, uploadTimestamp: response.data.uploadTimestamp }); // Output: { fileName: 'report.pdf', contentType: 'application/pdf', contentLength: 1048576, ... } } catch (err) { console.error('Get file info failed:', err.response?.data || err.message); } } ``` -------------------------------- ### Create Application Key - JavaScript Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Creates a new application key with specified capabilities and optional restrictions on bucket and file prefix. Requires a list of capabilities and a key name. Optionally accepts duration, bucket ID, and name prefix. Outputs key details including the application key ID and name, but the key itself is only shown once. ```javascript async function createKey() { await b2.authorize(); try { const response = await b2.createKey({ capabilities: [ 'listBuckets', 'listFiles', 'readFiles', 'writeFiles' ], keyName: 'my-app-key', validDurationInSeconds: 86400, // 24 hours (optional) bucketId: '4a48fe8875c6214145260818', // Restrict to bucket (optional) namePrefix: 'uploads/' // Restrict to file prefix (optional) }); console.log('Key created:', { applicationKeyId: response.data.applicationKeyId, applicationKey: response.data.applicationKey, // Only shown once! keyName: response.data.keyName, capabilities: response.data.capabilities, expirationTimestamp: response.data.expirationTimestamp }); // IMPORTANT: Save applicationKey - it's only returned once } catch (err) { console.error('Create key failed:', err.response?.data || err.message); } } ``` -------------------------------- ### Instantiate and Authorize Backblaze B2 Client (Node.js) Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md Demonstrates how to instantiate the Backblaze B2 client with credentials and authorize the connection. Authorization is required before making other API calls and typically lasts for 24 hours. ```javascript const B2 = require('backblaze-b2'); const b2 = new B2({ applicationKeyId: 'applicationKeyId', // or accountId: 'accountId' applicationKey: 'applicationKey' // or masterApplicationKey }); async function authorizeB2() { try { await b2.authorize(); console.log('Authorization successful'); } catch (err) { console.log('Error authorizing:', err); } } ``` -------------------------------- ### Initialize Backblaze B2 SDK Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md Initializes the Backblaze B2 SDK with provided credentials. Supports optional configuration for Axios instance and retry logic. The SDK functions return promises that resolve with the B2 API response. ```javascript const B2 = require('backblaze-b2'); const b2 = new B2({ applicationKeyId: 'applicationKeyId', applicationKey: 'applicationKey', axios: { // overrides the axios instance default config }, retry: { retries: 3 } }); ``` -------------------------------- ### List Application Keys - JavaScript Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Lists all application keys associated with the account. Allows pagination using maxKeyCount and startApplicationKeyId. Outputs a list of key details and the next application key ID for further pagination. ```javascript async function listKeys() { await b2.authorize(); try { const response = await b2.listKeys({ maxKeyCount: 10, startApplicationKeyId: '' // For pagination }); console.log('Application keys:', response.data.keys.map(k => ({ keyName: k.keyName, applicationKeyId: k.applicationKeyId, capabilities: k.capabilities, bucketId: k.bucketId, expirationTimestamp: k.expirationTimestamp }))); console.log('Next key ID:', response.data.nextApplicationKeyId); // Output: [{ keyName: 'my-app-key', applicationKeyId: '...', capabilities: [...] }] } catch (err) { console.error('List keys failed:', err.response?.data || err.message); } } ``` -------------------------------- ### Basic Promise Usage with Backblaze B2 Client (Node.js) Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md Illustrates the fundamental pattern for interacting with the Backblaze B2 library using promises. All actions return a promise that can be handled with .then() for success and error callbacks. ```javascript b2.instanceFunction(arg1, arg2).then( successFn(response) { ... }, errorFn(err) { ... } ); ``` -------------------------------- ### Create Bucket API Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Creates a new bucket in your Backblaze B2 account. Bucket names must be globally unique and adhere to specific naming conventions. ```APIDOC ## POST /b2api/v2/b2_create_bucket ### Description Creates a new bucket in your B2 account. Bucket names must be globally unique across all B2 accounts, between 6-50 characters, and contain only alphanumeric characters and hyphens. ### Method POST ### Endpoint /b2api/v2/b2_create_bucket ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **bucketName** (string) - Required - The desired name for the new bucket. Must be globally unique. - **bucketType** (string) - Required - Specifies the access level of the bucket. Can be 'allPrivate' or 'allPublic'. ### Request Example ```javascript async function createBucket() { await b2.authorize(); try { const response = await b2.createBucket({ bucketName: 'my-unique-bucket-name', bucketType: 'allPrivate' // or 'allPublic' }); console.log('Bucket created:', { bucketId: response.data.bucketId, bucketName: response.data.bucketName, bucketType: response.data.bucketType }); } catch (err) { console.error('Create bucket failed:', err.response?.data || err.message); } } ``` ### Response #### Success Response (200) - **bucketId** (string) - The unique identifier for the newly created bucket. - **bucketName** (string) - The name of the created bucket. - **bucketType** (string) - The access type of the bucket ('allPrivate' or 'allPublic'). #### Response Example ```json { "bucketId": "4a48fe8875c6214145260818", "bucketName": "my-unique-bucket-name", "bucketType": "allPrivate" } ``` ``` -------------------------------- ### Key Management API Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md API endpoints for creating, deleting, and listing API keys. ```APIDOC ## POST /b2_create_key ### Description Creates a new API key with specified capabilities and restrictions. ### Method POST ### Endpoint /b2_create_key ### Parameters #### Request Body - **capabilities** (array) - Required - An array of strings representing the key's capabilities (e.g., 'readFiles', 'writeFiles'). Use `b2.KEY_CAPABILITIES` for predefined options. - **keyName** (string) - Required - A name for the key (alphanumeric and '-' only, max 100 characters). - **validDurationInSeconds** (integer) - Optional - The duration in seconds for which the key will be valid. - **bucketId** (string) - Optional - Restricts the key's access to a specific bucket. - **namePrefix** (string) - Optional - Restricts the key's access to files with a specific prefix. ### Request Example ```json { "capabilities": ["readFiles"], "keyName": "my-key-1", "validDurationInSeconds": 3600, "bucketId": "bucketId", "namePrefix": "prefix_" } ``` ### Response #### Success Response (200) - **applicationKeyId** (string) - The ID of the newly created key. - **applicationKey** (string) - The secret key itself (should be stored securely). - **keyName** (string) - The name of the key. - **capabilities** (array) - The capabilities assigned to the key. - **bucketId** (string) - The bucket ID associated with the key, if any. - **namePrefix** (string) - The name prefix associated with the key, if any. - **expirationTimestamp** (integer) - The timestamp when the key will expire, if applicable. #### Response Example ```json { "applicationKeyId": "exampleKeyId", "applicationKey": "exampleSecretKey", "keyName": "my-key-1", "capabilities": ["readFiles"], "bucketId": "exampleBucketId", "namePrefix": "prefix_", "expirationTimestamp": 1678890000 } ``` --- ## POST /b2_delete_key ### Description Deletes an existing API key. ### Method POST ### Endpoint /b2_delete_key ### Parameters #### Request Body - **applicationKeyId** (string) - Required - The ID of the key to delete. ### Request Example ```json { "applicationKeyId": "exampleKeyId" } ``` ### Response #### Success Response (200) - **applicationKeyId** (string) - The ID of the deleted key. #### Response Example ```json { "applicationKeyId": "exampleKeyId" } ``` --- ## POST /b2_list_keys ### Description Lists available API keys, with optional filtering and pagination. ### Method POST ### Endpoint /b2_list_keys ### Parameters #### Query Parameters - **maxKeyCount** (integer) - Optional - The maximum number of keys to return. - **startApplicationKeyId** (string) - Optional - The ID of the key to start listing from (for pagination). ### Request Example ```json { "maxKeyCount": 10, "startApplicationKeyId": "previousKeyId" } ``` ### Response #### Success Response (200) - **keys** (array) - An array of key objects, each containing details like `applicationKeyId`, `keyName`, `capabilities`, etc. - **nextApplicationKeyId** (string) - The ID of the next key to start from if `maxKeyCount` was set and there are more keys. #### Response Example ```json { "keys": [ { "applicationKeyId": "keyId1", "keyName": "key1", "capabilities": ["readFiles"] }, { "applicationKeyId": "keyId2", "keyName": "key2", "capabilities": ["writeFiles"] } ], "nextApplicationKeyId": "keyId2" } ``` ``` -------------------------------- ### Configure Axios for Backblaze B2 Node.js Library Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Demonstrates how to configure the underlying axios instance for custom timeouts, headers, and request behavior. This includes setting global defaults and overriding them for specific requests. The `axios` option in the constructor sets global defaults, while the `axios` property within API call arguments allows per-request overrides. `axiosOverride` can be used for forceful overrides. ```javascript const B2 = require('backblaze-b2'); // Global axios configuration const b2 = new B2({ applicationKeyId: 'your-application-key-id', applicationKey: 'your-application-key', axios: { timeout: 60000, headers: { 'User-Agent': 'MyApp/1.0' } }, retry: { retries: 5, retryDelay: (retryCount) => retryCount * 1000 } }); async function customRequest() { await b2.authorize(); // Per-request axios configuration const response = await b2.listBuckets({ axios: { timeout: 10000, headers: { 'X-Custom-Header': 'custom-value' } }, // axiosOverride can forcefully override any property (use with caution) axiosOverride: { maxRedirects: 0 } }); console.log('Buckets:', response.data.buckets); } ``` -------------------------------- ### Upload File using JavaScript Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Uploads a file to a specified bucket. It first obtains an upload URL and then sends the file data. This method supports progress monitoring and custom metadata. Requires the 'fs' and 'path' modules. ```javascript const fs = require('fs'); const path = require('path'); async function uploadFile() { await b2.authorize(); try { // Step 1: Get upload URL for the bucket const uploadUrlResponse = await b2.getUploadUrl({ bucketId: '4a48fe8875c6214145260818' }); // Step 2: Read file and upload const filePath = './my-document.pdf'; const fileData = fs.readFileSync(filePath); const fileName = path.basename(filePath); const response = await b2.uploadFile({ uploadUrl: uploadUrlResponse.data.uploadUrl, uploadAuthToken: uploadUrlResponse.data.authorizationToken, fileName: fileName, data: fileData, mime: 'application/pdf', info: { 'author': 'john-doe', 'description': 'quarterly-report' }, onUploadProgress: (event) => { const percent = Math.round((event.loaded / event.total) * 100); console.log(`Upload progress: ${percent}%`); } }); console.log('File uploaded:', { fileId: response.data.fileId, fileName: response.data.fileName, contentLength: response.data.contentLength, contentSha1: response.data.contentSha1 }); // Output: { fileId: '4_z4a48fe8875c6214145260818_f1...', fileName: 'my-document.pdf', ... } } catch (err) { console.error('Upload failed:', err.response?.data || err.message); } } ``` -------------------------------- ### Create API Key - JavaScript Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md Creates a new Backblaze B2 API key with specified capabilities and optional restrictions. Capabilities can be defined as strings or using the provided constants. The key can have a duration, be restricted to a specific bucket, or a file name prefix. ```javascript b2.createKey({ capabilities: [ 'readFiles', b2.KEY_CAPABILITIES.READ_FILES, // see https://www.backblaze.com/b2/docs/b2_create_key.html for full list ], keyName: 'my-key-1', // letters, numbers, and '-' only, <=100 chars validDurationInSeconds: 3600, // expire after duration (optional) bucketId: 'bucketId', // restrict access to bucket (optional) namePrefix: 'prefix_', // restrict access to file prefix (optional) // ...common arguments (optional) }); // returns promise ``` -------------------------------- ### List Buckets API Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Retrieves a list of all buckets associated with your account. If using a restricted application key, only buckets accessible by that key will be returned. ```APIDOC ## POST /b2api/v2/b2_list_buckets ### Description Retrieves a list of all buckets associated with your account. When using a restricted application key, only buckets the key has access to will be returned. ### Method POST ### Endpoint /b2api/v2/b2_list_buckets ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript async function listBuckets() { await b2.authorize(); try { const response = await b2.listBuckets(); console.log('Buckets:', response.data.buckets.map(b => ({ id: b.bucketId, name: b.bucketName, type: b.bucketType }))); } catch (err) { console.error('List buckets failed:', err.response?.data || err.message); } } ``` ### Response #### Success Response (200) - **buckets** (array) - An array of bucket objects. - **bucketId** (string) - The unique identifier for the bucket. - **bucketName** (string) - The name of the bucket. - **bucketType** (string) - The access type of the bucket ('allPrivate' or 'allPublic'). #### Response Example ```json { "buckets": [ { "bucketId": "4a48fe8875c6214145260818", "bucketName": "my-bucket", "bucketType": "allPrivate" }, ... ] } ``` ``` -------------------------------- ### Download File by Name from Backblaze B2 Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Downloads a file from a Backblaze B2 bucket using its name and path. Allows specifying response type and provides progress updates. Saves the downloaded content to a local file. Requires authorization and the 'fs' module. ```javascript const fs = require('fs'); async function downloadFileByName() { await b2.authorize(); try { const response = await b2.downloadFileByName({ bucketName: 'my-bucket', fileName: 'documents/report.pdf', responseType: 'arraybuffer', onDownloadProgress: (event) => { const percent = Math.round((event.loaded / event.total) * 100); console.log(`Download progress: ${percent}%`); } }); // Save to local file fs.writeFileSync('./downloaded-report.pdf', Buffer.from(response.data)); console.log('File downloaded successfully'); console.log('Content-Type:', response.headers['content-type']); console.log('Content-Length:', response.headers['content-length']); } catch (err) { console.error('Download failed:', err.response?.data || err.message); } } ``` -------------------------------- ### Backblaze B2 Bucket Management Functions Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md Provides JavaScript functions for managing Backblaze B2 buckets, including authorization, creation, deletion, listing, retrieval, and updating. Each function returns a promise that resolves with the API response. Common arguments can be passed for request-level configuration. ```javascript // Common arguments for API calls const common_args = { axios: { timeout: 30000 }, axiosOverride: {} } // Authorize with provided credentials b2.authorize(common_args); // Create a bucket b2.createBucket({ bucketName: 'bucketName', bucketType: 'bucketType' // 'allPublic' or 'allPrivate' // ...common_args }); // Delete a bucket b2.deleteBucket({ bucketId: 'bucketId' // ...common_args }); // List buckets b2.listBuckets(common_args); // Get a specific bucket b2.getBucket({ bucketName: 'bucketName', bucketId: 'bucketId' // optional // ...common_args }); // Update a bucket b2.updateBucket({ bucketId: 'bucketId', bucketType: 'bucketType' // ...common_args }); ``` -------------------------------- ### Upload File API Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Uploads a file to a specified bucket. This process involves first obtaining an upload URL and then sending the file data. It supports progress monitoring and custom metadata. ```APIDOC ## POST /b2api/v2/b2_upload ### Description Uploads a file to a bucket. First obtain an upload URL, then send the file data. Supports progress monitoring and custom metadata headers. ### Method POST ### Endpoint /b2api/v2/b2_upload ### Parameters #### Query Parameters - **bucketId** (string) - Required - The ID of the bucket to upload the file to. #### Request Body - **fileName** (string) - Required - The name of the file to upload. - **data** (Buffer/Stream) - Required - The file data to upload. - **mime** (string) - Optional - The MIME type of the file. - **info** (object) - Optional - Custom metadata for the file. Keys are prefixed with 'X-Bz-Info-'. - **author** (string) - Example metadata field. - **description** (string) - Example metadata field. - **onUploadProgress** (function) - Optional - Callback function to monitor upload progress. ### Request Example ```json { "fileName": "my-document.pdf", "data": "", "mime": "application/pdf", "info": { "author": "john-doe", "description": "quarterly-report" } } ``` ### Response #### Success Response (200) - **fileId** (string) - The unique identifier for the uploaded file. - **fileName** (string) - The name of the uploaded file. - **bucketId** (string) - The ID of the bucket where the file was uploaded. - **contentLength** (integer) - The size of the file in bytes. - **contentSha1** (string) - The SHA1 hash of the file content. - **uploadTimestamp** (integer) - The timestamp when the file was uploaded. - **fileInfo** (object) - The metadata associated with the file. #### Response Example ```json { "fileId": "4_z4a48fe8875c6214145260818_f1...", "fileName": "my-document.pdf", "bucketId": "4a48fe8875c6214145260818", "contentLength": 123456, "contentSha1": "a1b2c3d4e5f678901234567890abcdef12345678", "uploadTimestamp": 1678886400000, "fileInfo": { "author": "john-doe", "description": "quarterly-report" } } ``` ``` -------------------------------- ### Create Backblaze B2 Bucket Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Creates a new bucket within your Backblaze B2 account. Bucket names must be globally unique, adhere to specific character and length constraints, and can be configured for private or public access. ```javascript async function createBucket() { await b2.authorize(); try { const response = await b2.createBucket({ bucketName: 'my-unique-bucket-name', bucketType: 'allPrivate' // or 'allPublic' }); console.log('Bucket created:', { bucketId: response.data.bucketId, bucketName: response.data.bucketName, bucketType: response.data.bucketType }); // Output: { bucketId: '4a48fe8875c6214145260818', bucketName: 'my-unique-bucket-name', bucketType: 'allPrivate' } } catch (err) { console.error('Create bucket failed:', err.response?.data || err.message); } } ``` -------------------------------- ### Backblaze B2 File Listing and Information Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md JavaScript functions for listing and retrieving information about files in Backblaze B2 buckets. Supports listing files by name, listing file versions, and retrieving specific file metadata. Parameters like bucket ID, file name, and limits can be specified. ```javascript // List file names b2.listFileNames({ bucketId: 'bucketId', startFileName: 'startFileName', maxFileCount: 100, delimiter: '', prefix: '' // ...common_args }); // List file versions b2.listFileVersions({ bucketId: 'bucketId', startFileName: 'startFileName', startFileId: 'startFileId', maxFileCount: 100 // ...common_args }); // List parts of a large file b2.listParts({ fileId: 'fileId', startPartNumber: 0, // optional maxPartCount: 100 // ...common_args }); // Get file information b2.getFileInfo({ fileId: 'fileId' // ...common_args }); ``` -------------------------------- ### List Files in Backblaze B2 Bucket with Filtering Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Lists files within a specified Backblaze B2 bucket. Supports filtering by prefix and delimiter for directory-like navigation, and pagination with maxFileCount. Requires bucketId and authorization. ```javascript async function listFileNames() { await b2.authorize(); try { const response = await b2.listFileNames({ bucketId: '4a48fe8875c6214145260818', prefix: 'documents/', delimiter: '/', maxFileCount: 100, startFileName: '' // For pagination }); console.log('Files:', response.data.files.map(f => ({ fileName: f.fileName, fileId: f.fileId, size: f.contentLength, uploadTimestamp: f.uploadTimestamp }))); console.log('Next file name:', response.data.nextFileName); // Output: [{ fileName: 'documents/report.pdf', fileId: '...', size: 1048576, ... }] } catch (err) { console.error('List files failed:', err.response?.data || err.message); } } ``` -------------------------------- ### Backblaze B2 File Operations (Hide, Delete, Download) Source: https://github.com/yakovkhalinsky/backblaze-b2/blob/master/README.md JavaScript functions for managing file visibility and deletion in Backblaze B2, as well as downloading files. Includes hiding files, deleting specific file versions, and downloading files by name or ID. Download progress can be monitored. ```javascript // Hide a file b2.hideFile({ bucketId: 'bucketId', fileName: 'fileName' // ...common_args }); // Delete a file version b2.deleteFileVersion({ fileId: 'fileId', fileName: 'fileName' // ...common_args }); // Download file by name b2.downloadFileByName({ bucketName: 'bucketName', fileName: 'fileName', responseType: 'arraybuffer', // e.g., 'arraybuffer', 'blob', 'json', 'text' onDownloadProgress: (event) => {} // ...common_args }); // Download file by fileId b2.downloadFileById({ fileId: 'fileId', responseType: 'arraybuffer', onDownloadProgress: (event) => {} // ...common_args }); ``` -------------------------------- ### List Backblaze B2 Buckets Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Retrieves a list of all buckets associated with the authenticated account. If a restricted application key is used, only buckets accessible by that key will be returned. ```javascript async function listBuckets() { await b2.authorize(); try { const response = await b2.listBuckets(); console.log('Buckets:', response.data.buckets.map(b => ({ id: b.bucketId, name: b.bucketName, type: b.bucketType }))); // Output: [{ id: '4a48fe8875c6214145260818', name: 'my-bucket', type: 'allPrivate' }, ...] } catch (err) { console.error('List buckets failed:', err.response?.data || err.message); } } ``` -------------------------------- ### Download File by ID from Backblaze B2 Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Downloads a file from Backblaze B2 using its unique file ID, useful when the bucket name and path are unknown. Supports response type configuration and download progress monitoring. Saves the file locally. Requires authorization and the 'fs' module. ```javascript const fs = require('fs'); async function downloadFileById() { await b2.authorize(); try { const response = await b2.downloadFileById({ fileId: '4_z4a48fe8875c6214145260818_f1190...', responseType: 'arraybuffer', onDownloadProgress: (event) => { if (event.total) { const percent = Math.round((event.loaded / event.total) * 100); console.log(`Download progress: ${percent}%`); } } }); fs.writeFileSync('./downloaded-file.pdf', Buffer.from(response.data)); console.log('File downloaded by ID successfully'); } catch (err) { console.error('Download failed:', err.response?.data || err.message); } } ``` -------------------------------- ### List All File Versions in Backblaze B2 Bucket Source: https://context7.com/yakovkhalinsky/backblaze-b2/llms.txt Retrieves a list of all file versions within a Backblaze B2 bucket, including hidden versions. Useful for accessing file history and performing rollbacks. Requires bucketId and authorization. ```javascript async function listFileVersions() { await b2.authorize(); try { const response = await b2.listFileVersions({ bucketId: '4a48fe8875c6214145260818', maxFileCount: 100, startFileName: '', startFileId: '' // For pagination }); console.log('File versions:', response.data.files.map(f => ({ fileName: f.fileName, fileId: f.fileId, action: f.action, // 'upload' or 'hide' uploadTimestamp: f.uploadTimestamp }))); // Output: [{ fileName: 'doc.pdf', fileId: '...', action: 'upload', ... }] } catch (err) { console.error('List file versions failed:', err.response?.data || err.message); } } ```