@backblaze-labs/b2-sdk - v0.1.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

    Properties

    Unique identifier for this bucket.

    Full bucket metadata as returned by the B2 API.

    name: string

    Human-readable bucket name.

    Methods

    • 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.

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

      Parameters

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

        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.

        • 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

          Server-side encryption for the destination file.

        • sourceFileId: FileId

          File ID of the source file to copy.

      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;
            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.

        • 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 }

        Optional flag for bypassing governance retention.

      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.

    • 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 its latest version is a hide marker.

      Parameters

      • fileName: string

        The exact file path to look up.

      Returns Promise<FileVersion | null>

      The latest FileVersion, or null if not found.

    • 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.

      Returns Promise<FileVersion>

      Metadata for the newly created hide marker.

    • Lists file names in this bucket (most recent versions only).

      Parameters

      • Optionaloptions: {
            delimiter?: string;
            pageSize?: number;
            prefix?: string;
            startFileName?: string;
        }

        Optional filtering and pagination settings.

        • Optionaldelimiter?: string

          Delimiter for virtual directory grouping (typically "/").

        • OptionalpageSize?: number

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

        • Optionalprefix?: string

          Only list files with names starting with this prefix.

        • OptionalstartFileName?: string

          Start listing after this file name (for pagination).

      Returns Promise<ListFileNamesResponse>

      A page of file versions with an optional continuation token.

    • Lists all file versions in this bucket, including hidden files.

      Parameters

      • Optionaloptions: {
            delimiter?: string;
            pageSize?: number;
            prefix?: string;
            startFileId?: FileId;
            startFileName?: string;
        }

        Optional filtering and pagination settings.

        • Optionaldelimiter?: string

          Delimiter for virtual directory grouping.

        • OptionalpageSize?: number

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

        • Optionalprefix?: string

          Only list files with names starting with this prefix.

        • OptionalstartFileId?: FileId

          Start listing after this file ID (for pagination within a file name).

        • OptionalstartFileName?: string

          Start listing after this file name (for pagination).

      Returns Promise<ListFileVersionsResponse>

      A page of file versions with an optional continuation token.

    • 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; 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.

        • OptionalstartFileId?: LargeFileId

          Start listing after this file ID (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

      • Optionaloptions: { delimiter?: string; prefix?: string } & PaginatorOptions

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

        • Optionaldelimiter?: string

          Delimiter for virtual directory grouping (typically '/').

        • Optionalprefix?: string

          Only yield files whose names start with this prefix.

      Returns AsyncIterableIterator<FileVersion>

      An async iterable of FileVersion entries.

      for await (const file of bucket.paginateFileNames({ prefix: 'photos/' })) {
      console.log(file.fileName, file.contentLength)
      }
    • Async iterator that yields every version of every file in the bucket, including hidden files and historical versions, automatically handling pagination via listFileVersions.

      The two-cursor (nextFileName, nextFileId) continuation that the raw endpoint exposes is threaded internally; callers iterate flat.

      Parameters

      • Optionaloptions: { delimiter?: string; prefix?: string } & PaginatorOptions

        Filter + pagination + abort options.

        • Optionaldelimiter?: string

          Delimiter for virtual directory grouping.

        • Optionalprefix?: string

          Only yield versions whose names start with this prefix.

      Returns AsyncIterableIterator<FileVersion>

      An async iterable of FileVersion entries.

    • 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.

    • 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<FileVersion | null>

      The deleted hide marker version, 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?: EncryptionSetting;
            ifRevisionIs?: number;
            lifecycleRules?: LifecycleRule[];
            replicationConfiguration?: ReplicationConfiguration;
        }

        Fields to update. Omitted fields are left unchanged.

        • OptionalbucketInfo?: Record<string, string>

          Replace custom bucket metadata.

        • OptionalbucketType?: BucketType

          Change the bucket access level.

        • OptionalcorsRules?: CorsRule[]

          Replace CORS rules.

        • OptionaldefaultRetention?: BucketRetentionPolicy

          Change default file retention policy.

        • OptionaldefaultServerSideEncryption?: EncryptionSetting

          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: {
            concurrency?: number;
            contentType?: string;
            fileInfo?: Record<string, string>;
            fileName: string;
            fileRetention?: FileRetentionValue;
            lastModifiedMillis?: number;
            legalHold?: LegalHoldValue;
            onProgress?: ProgressListener;
            partSize?: number;
            resume?: boolean;
            resumeFileId?: LargeFileId;
            serverSideEncryption?: EncryptionSetting;
            signal?: AbortSignal;
            source: ContentSource;
        }

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

        • Optionalconcurrency?: number

          Number of concurrent part uploads for large files.

        • OptionalcontentType?: string

          MIME type. Defaults to "b2/x-auto" (auto-detected by B2).

        • OptionalfileInfo?: Record<string, string>

          Custom key-value metadata stored with the file.

        • fileName: string

          Destination file name (path) in the bucket.

        • OptionalfileRetention?: FileRetentionValue

          File retention policy (requires file lock on the bucket).

        • OptionallastModifiedMillis?: number

          Last-modified timestamp in milliseconds since epoch.

        • OptionallegalHold?: LegalHoldValue

          Legal hold status for the file.

        • OptionalonProgress?: ProgressListener

          Callback invoked with upload progress events.

        • OptionalpartSize?: number

          Part size override for multipart uploads, in bytes.

        • Optionalresume?: boolean

          Resume an unfinished multipart upload for this file name when one exists. Only consulted on the large-file path (source size greater than recommendedPartSize). On the small-file path this option is silently ignored. Sliceable sources only — StreamSource rejects resume because it can't replay parts.

        • OptionalresumeFileId?: LargeFileId

          Resume into a specific large-file ID. Overrides the resume discovery path. The local partSize must match the server-side plan.

        • OptionalserverSideEncryption?: EncryptionSetting

          Server-side encryption settings.

        • Optionalsignal?: AbortSignal

          Abort signal for cancelling the upload.

        • source: ContentSource

          Data source to upload. Use BufferSource, BlobSource, or StreamSource.

      Returns Promise<FileVersion>

      Metadata for the uploaded file version.