@backblaze-labs/b2-sdk - v0.4.0
    Preparing search index...

    Class Bucket

    Handle to a B2 bucket providing upload, download, listing, and management operations.

    Obtained via B2Client.createBucket, B2Client.listBuckets, or B2Client.getBucket.

    const bucket = await client.getBucket('my-bucket')
    await bucket.upload({ fileName: 'hello.txt', source: new BufferSource(data) })
    Index

    Unique identifier for this bucket.

    Full bucket metadata as returned by the B2 API.

    name: string

    Human-readable bucket name.

    • Adds (or replaces, matched by fileNamePrefix) a single lifecycle rule while leaving any other rules untouched.

      Matching on prefix mirrors B2's own data model: each unique prefix can have at most one rule, and a b2_update_bucket call that contains two rules with the same prefix is rejected. The helper enforces this for the caller.

      Parameters

      Returns Promise<BucketInfo>

      The updated bucket metadata.

    • Adds (or replaces by replicationRuleName) a single replication rule on this bucket while leaving any other rules, the source key, and the destination key mapping untouched.

      When this is the very first source-side rule, sourceApplicationKeyId must be supplied to seed asReplicationSource.sourceApplicationKeyId; for subsequent calls the existing source key is reused unless the caller explicitly overrides it.

      Parameters

      • rule: ReplicationRule

        The replication rule to add or replace.

      • Optionaloptions: { sourceApplicationKeyId?: ApplicationKeyId }

        Optional source application key ID override (or seed when no source side exists yet).

      Returns Promise<BucketInfo>

      The updated bucket metadata.

      If no source-side replication exists yet and the caller did not supply sourceApplicationKeyId.

      If the caller is not authorized to read current replication settings.

    • Creates a server-side copy of a file within or across buckets.

      Parameters

      • options: {
            contentType?: string;
            destinationBucketId?: BucketId;
            destinationServerSideEncryption?: EncryptionSetting;
            fileInfo?: Record<string, string>;
            fileName: string;
            metadataDirective?: MetadataDirective;
            serverSideEncryption?: EncryptionSetting;
            signal?: AbortSignal;
            sourceFileId: FileId;
            sourceServerSideEncryption?: EncryptionSetting;
        }

        Copy configuration including source file ID and destination name.

        • OptionalcontentType?: string

          Override content type (only with REPLACE metadata directive).

        • OptionaldestinationBucketId?: BucketId

          Target bucket ID. Defaults to this bucket if omitted.

        • OptionaldestinationServerSideEncryption?: EncryptionSetting

          Server-side encryption for the destination file. Preferred over serverSideEncryption.

        • OptionalfileInfo?: Record<string, string>

          Override file info (only with REPLACE metadata directive).

        • fileName: string

          Destination file name in the target bucket.

        • OptionalmetadataDirective?: MetadataDirective

          Whether to copy or replace file metadata.

        • OptionalserverSideEncryption?: EncryptionSetting

          Renamed to destinationServerSideEncryption for consistency with multipart copy. Still honored as a fallback when the new field is absent.

        • Optionalsignal?: AbortSignal

          Optional abort signal for cancelling the copy request.

        • sourceFileId: FileId

          File ID of the source file to copy.

        • OptionalsourceServerSideEncryption?: EncryptionSetting

          SSE-C settings for the source if it was uploaded with SSE-C.

      Returns Promise<FileVersion>

      Metadata for the newly created file version.

    • Copies a file via the server-side multipart protocol. Each part is copied by reference through b2_copy_part; data never traverses the client. Falls back to a single copyFile call when the source fits within a single part.

      Parameters

      • options: {
            concurrency?: number;
            contentType?: string;
            destinationBucketId?: BucketId;
            destinationServerSideEncryption?: EncryptionSetting;
            fileInfo?: Record<string, string>;
            fileName: string;
            onCleanupFailure?: CleanupFailureListener;
            partSize?: number;
            signal?: AbortSignal;
            sourceFileId: FileId;
            sourceServerSideEncryption?: EncryptionSetting;
        }

        Copy parameters including source file ID, destination name, part size, and concurrency.

        • Optionalconcurrency?: number

          Maximum number of parts copied in parallel. Defaults to the SDK-wide transfer concurrency.

        • OptionalcontentType?: string

          Override content type for the destination.

        • OptionaldestinationBucketId?: BucketId

          Target bucket ID. Defaults to this bucket if omitted.

        • OptionaldestinationServerSideEncryption?: EncryptionSetting

          Server-side encryption for the destination file.

        • OptionalfileInfo?: Record<string, string>

          Custom file info for the destination.

        • fileName: string

          Destination file name in the target bucket.

        • OptionalonCleanupFailure?: CleanupFailureListener

          Callback invoked if best-effort cancellation fails, or if cancellation is skipped because b2_finish_large_file may already have committed.

        • OptionalpartSize?: number

          Part size in bytes. Defaults to the account's recommended part size.

        • Optionalsignal?: AbortSignal

          Optional abort signal. Aborting cancels any remaining parts and triggers a best-effort cancelLargeFile on the unfinished upload.

        • sourceFileId: FileId

          File ID of the source file to copy.

        • OptionalsourceServerSideEncryption?: EncryptionSetting

          SSE-C settings for the source if it was uploaded with SSE-C.

      Returns Promise<FileVersion>

      Metadata for the newly created destination file version.

    • Permanently deletes this bucket. The bucket must be empty (no file versions).

      Returns Promise<BucketInfo>

      The deleted bucket metadata.

    • Async generator that streams every file version in the bucket (optionally filtered by prefix) and deletes each one. Yields a DeleteAllEvent per file version. With dryRun: true, no deletes are performed but skip events are still emitted.

      Parameters

      • Optionaloptions: { dryRun?: boolean; pageSize?: number; prefix?: string }

        Optional prefix filter, page size, and dry-run flag.

        • OptionaldryRun?: boolean

          If true, yield skip events without actually deleting anything.

        • OptionalpageSize?: number

          Number of file versions fetched per API page (default 1000).

        • Optionalprefix?: string

          Only delete file versions whose names start with this prefix.

      Returns AsyncGenerator<DeleteAllEvent>

      An async generator of per-file events.

    • Permanently deletes a specific file version. Both file name and file ID are required.

      If the file is under Object Lock retention, B2 will reject the delete: compliance-mode files cannot be deleted until the retention expires; governance-mode files require bypassGovernance: true AND a calling key with the bypassGovernance capability. Files on legal hold cannot be deleted by anyone until the hold is removed.

      Parameters

      • fileName: string

        The file path of the version to delete.

      • fileId: FileId

        The unique identifier of the file version to delete.

      • Optionaloptions: { bypassGovernance?: boolean; signal?: AbortSignal }

        Optional governance and abort controls.

      Returns Promise<void>

    • Deletes many file versions with bounded concurrency. Errors from individual deletes are collected and returned rather than thrown, so partial success does not abort the run.

      When options.signal is supplied and aborted, in-flight deletes complete (they're already on the wire), but no new deletes start after the abort fires. Subsequent targets are short-circuited to an error entry so the result tally reflects what actually happened.

      Parameters

      • targets: readonly DeleteTarget[]

        File versions to delete.

      • Optionaloptions: { concurrency?: number; signal?: AbortSignal }

        Optional concurrency override and abort signal. Concurrency defaults to the SDK-wide bulk-metadata setting (currently 10, higher than transfer concurrency because each task is a single tiny API round-trip).

      Returns Promise<DeleteManyResult>

      A summary of successes and per-target errors.

    • Downloads a file from this bucket by name. Pass method: 'HEAD' in options to fetch only the response headers (file metadata) without streaming the body.

      Parameters

      • fileName: string

        The file name (path) to download.

      • Optionaloptions: DownloadCallOptions

        Optional method, range, SSE-C decryption, response-header overrides, and abort signal.

      Returns Promise<DownloadResult>

      The download result containing response headers and a readable body stream.

    • Returns a B2Object handle for a specific file name in this bucket.

      Parameters

      • fileName: string

        The file path within the bucket.

      Returns B2Object

      A B2Object handle bound to this bucket and file name.

    • Returns the current default Object Lock retention policy for new uploads to this bucket, refetched from B2.

      Returns Promise<BucketDefaultRetention | undefined>

      The default BucketDefaultRetention, or undefined if the file lock configuration is not readable. B2 represents no bucket default retention as { mode: null, period: null }.

    • Gets a download authorization token scoped to a file name prefix in this bucket.

      Parameters

      • fileNamePrefix: string

        Only authorize downloads of files starting with this prefix.

      • validDurationInSeconds: number

        How long the authorization is valid (1-604800 seconds).

      Returns Promise<DownloadAuthorizationResponse>

      The download authorization response containing a time-limited token.

    • Looks up the latest visible version of a file by name. Uses listFileNames under the hood; returns null when the file does not exist or is hidden.

      Parameters

      • fileName: string

        The exact file path to look up.

      Returns Promise<FileVersion | null>

      The latest FileVersion, or null if not found.

    • Returns the current cross-region replication configuration, refetched from B2.

      Use this when you need to read replication state without composing a write. For add/remove flows the helper methods below handle the refresh-then-set sequence for you.

      Returns Promise<ReadableReplicationConfiguration>

      The current readable replication wrapper. Its value is null when no replication is configured or when the caller is not authorized to read replication settings.

    • Fetches the response headers (file metadata) for a file via HTTP HEAD. Returns a body-less result so callers never have to drain the (logically empty) HEAD body themselves.

      Use this for metadata-only checks like "does this file exist", "what is its current SHA-1", "what is its Content-Length". For full file retrieval use Bucket.download.

      Parameters

      • fileName: string

        The file name (path) to inspect.

      • Optionaloptions: HeadCallOptions

        Optional range, SSE-C decryption, response-header overrides, and abort signal. Same shape as Bucket.download's options minus method (always HEAD) and onProgress (no body).

      Returns Promise<HeadResult>

      Parsed download headers (content type, SHA-1, file info, etc.).

      const { headers } = await bucket.head('photos/2026/sunset.jpg')
      console.log(headers.contentLength, headers.contentSha1)
    • Hides a file by creating a hide marker. The file remains in version history but is no longer visible in listFileNames.

      Parameters

      • fileName: string

        The file path to hide.

      • Optionaloptions: { signal?: AbortSignal }

        Optional request controls such as an abort signal.

      Returns Promise<FileVersion>

      Metadata for the newly created hide marker.

    • Lists large files in this bucket that were started but never finished or cancelled. Wraps b2_list_unfinished_large_files.

      Parameters

      • Optionaloptions: {
            namePrefix?: string;
            pageSize?: number;
            signal?: AbortSignal;
            startFileId?: LargeFileId;
        }

        Optional pagination filters.

        • OptionalnamePrefix?: string

          Restrict results to files whose name starts with this prefix.

        • OptionalpageSize?: number

          Maximum number of files to return per request (1-100). Forwarded to the raw API's maxFileCount parameter.

        • Optionalsignal?: AbortSignal

          Abort signal for cancelling the list request.

        • OptionalstartFileId?: LargeFileId

          Start listing at this file ID, inclusive (for pagination).

      Returns Promise<ListUnfinishedLargeFilesResponse>

      The page of unfinished large files plus a continuation token.

    • Async iterator that yields the latest visible version of every file in the bucket, automatically handling pagination via listFileNames.

      Hidden files (those whose latest version is a hide marker) are NOT yielded by this iterator. Use paginateFileVersions when you need full version history.

      Parameters

      Returns AsyncIterableIterator<FileNameListEntry>

      An async iterable of concrete file versions. Passing delimiter selects the delimiter overload, which may also yield virtual folders.

      for await (const file of bucket.paginateFileNames({ prefix: 'photos/' })) {
      console.log(file.fileName, file.contentLength)
      }
    • Async iterator that yields the latest visible version of every file in the bucket, automatically handling pagination via listFileNames.

      Hidden files (those whose latest version is a hide marker) are NOT yielded by this iterator. Use paginateFileVersions when you need full version history.

      Parameters

      • Optionaloptions: BucketPaginateFileNamesOptions

        Filter + pagination + abort options. pageSize is forwarded to b2_list_file_names's maxFileCount (default 1000, B2-capped at 10000).

      Returns AsyncIterableIterator<ListedFileVersion>

      An async iterable of concrete file versions. Passing delimiter selects the delimiter overload, which may also yield virtual folders.

      for await (const file of bucket.paginateFileNames({ prefix: 'photos/' })) {
      console.log(file.fileName, file.contentLength)
      }
    • Async iterator that yields the latest visible version of every file in the bucket, automatically handling pagination via listFileNames.

      Hidden files (those whose latest version is a hide marker) are NOT yielded by this iterator. Use paginateFileVersions when you need full version history.

      Parameters

      Returns AsyncIterableIterator<FileNameListEntry>

      An async iterable of concrete file versions. Passing delimiter selects the delimiter overload, which may also yield virtual folders.

      for await (const file of bucket.paginateFileNames({ prefix: 'photos/' })) {
      console.log(file.fileName, file.contentLength)
      }
    • Async iterator that yields every uploaded part for a specific large file, automatically handling pagination via listParts.

      Parameters

      • largeFileId: LargeFileId

        The unfinished large file to enumerate parts of.

      • Optionaloptions: PaginatorOptions

        Pagination + abort options. pageSize is B2-capped at 1000 for this endpoint; the default is 1000.

      Returns AsyncIterableIterator<PartInfo>

      An async iterable of PartInfo entries.

    • Async iterator that yields every unfinished large file in the bucket, automatically handling pagination via listUnfinishedLargeFiles.

      Useful for janitorial scripts that want to inspect or cancel abandoned multipart uploads (typically followed by cancelLargeFile on the underlying raw client).

      Parameters

      • Optionaloptions: { namePrefix?: string } & PaginatorOptions

        Filter + pagination + abort options. pageSize is B2-capped at 100 for this endpoint.

        • OptionalnamePrefix?: string

          Only yield large files whose names start with this prefix.

      Returns AsyncIterableIterator<UnfinishedLargeFile>

      An async iterable of unfinished-large-file metadata entries.

    • Removes a single lifecycle rule by prefix. No-ops cleanly when the rule is not present.

      Parameters

      • fileNamePrefix: string

        The prefix of the rule to remove.

      Returns Promise<BucketInfo>

      The updated bucket metadata.

    • Removes a single replication rule by name. No-ops cleanly when the rule is not present (returns the unchanged-but-revision-bumped bucket info).

      Parameters

      • replicationRuleName: string

        Name of the rule to remove.

      Returns Promise<BucketInfo>

      The updated bucket metadata.

      If the caller is not authorized to read current replication settings.

    • Sets (or clears, by passing { mode: 'none', period: null }) the default Object Lock retention policy applied to new uploads.

      Object Lock must already be enabled on the bucket. Buckets created without fileLockEnabled: true cannot accept a default retention policy and B2 will reject this call.

      Parameters

      Returns Promise<BucketInfo>

      The updated bucket metadata.

    • Replaces this bucket's lifecycle rules in their entirety.

      Parameters

      • rules: readonly LifecycleRule[]

        The new rule set. Pass [] to remove all lifecycle automation.

      Returns Promise<BucketInfo>

      The updated bucket metadata.

    • Replaces this bucket's complete replication configuration.

      Parameters

      • replication: ReplicationConfiguration

        The new configuration. Pass an empty source/destination pair ({ asReplicationSource: null, asReplicationDestination: null }) to clear replication entirely.

      Returns Promise<BucketInfo>

      The updated bucket metadata.

    • Removes the latest hide marker for a file, restoring visibility of the previous upload. Returns the deleted hide marker, or null if there was no hide marker to remove (file is already visible or does not exist).

      Parameters

      • fileName: string

        The file path to unhide.

      Returns Promise<ListedHideFileVersion | null>

      The deleted listed hide-marker row, or null if nothing was hidden.

    • Updates bucket settings such as type, CORS, lifecycle rules, and encryption.

      Parameters

      • options: {
            bucketInfo?: Record<string, string>;
            bucketType?: BucketType;
            corsRules?: CorsRule[];
            defaultRetention?: BucketRetentionPolicy;
            defaultServerSideEncryption?: BucketDefaultServerSideEncryptionSetting;
            ifRevisionIs?: number;
            lifecycleRules?: LifecycleRule[];
            replicationConfiguration?: ReplicationConfiguration;
        }

        Fields to update. Omitted fields are left unchanged.

        • OptionalbucketInfo?: Record<string, string>

          Replace custom bucket metadata. Keys must be 1-50 UTF-8 bytes, must not start with b2-, and all values together must be at most 10,000 UTF-8 bytes. Keys must match BUCKET_INFO_KEY_PATTERN. There is no bucketInfo pair-count cap.

        • OptionalbucketType?: BucketType

          Change the bucket access level.

        • OptionalcorsRules?: CorsRule[]

          Replace CORS rules. A bucket may have at most 100 rules; rule names must be unique, 6-63 characters, match [A-Za-z0-9-], and not start with b2-. Each rule must be less than 1,000 UTF-8 bytes across its name, origins, operations, allowed headers, and exposed headers. maxAgeSeconds must be at most 86,400.

        • OptionaldefaultRetention?: BucketRetentionPolicy

          Change default file retention policy.

        • OptionaldefaultServerSideEncryption?: BucketDefaultServerSideEncryptionSetting

          Change default server-side encryption.

        • OptionalifRevisionIs?: number

          Optimistic locking: only update if the bucket revision matches.

        • OptionallifecycleRules?: LifecycleRule[]

          Replace lifecycle rules.

        • OptionalreplicationConfiguration?: ReplicationConfiguration

          Update replication configuration.

      Returns Promise<BucketInfo>

      Updated bucket metadata.

    • Updates the file retention policy for a specific file version. Requires file lock on the bucket.

      Parameters

      • fileName: string

        The file path of the version to update.

      • fileId: FileId

        The unique identifier of the file version.

      • retention: FileRetentionValue

        The new retention policy to apply.

      • Optionaloptions: { bypassGovernance?: boolean }

        Optional flags. Set bypassGovernance: true to shorten governance-mode retention.

      Returns Promise<UpdateFileRetentionResponse>

      The updated file retention metadata.

    • Uploads a file to this bucket. Automatically uses multipart upload for files larger than the recommended part size.

      Parameters

      • options: BucketUploadOptions

        Upload configuration including file name, source data, and optional settings.

      Returns Promise<FileVersion>

      Metadata for the uploaded file version.