backblaze-b2 Node.js Library

repository·master·Indexed 41 days ago

https://github.com/yakovkhalinsky/backblaze-b2

A customizable Node.js client for the Backblaze B2 cloud storage service, version 1.7.1. Built on axios with built-in automatic retries, it provides modules for authentication, bucket management, file uploads (including multipart uploads for large files), downloads, and API key management.

Tokens
2.9K
Snippets
7
Records
13
Agent score
52%

What's inside backblaze-b2

  1. Customize axios requests at the instance or request level

    master

    The library allows you to pass axios configuration at two levels:

    1. Global Level: Pass an axios object during new B2({...}) instantiation to set default configurations for all requests.
    2. Request Level: Pass axios or axiosOverride arguments to specific method calls.

    Behavioral difference:

    • axios: Properties are added to the request object only if they do not conflict with existing properties. It performs a recursive merge.
    • axiosOverride: Properties are added by overriding conflicting properties. Use this with caution.

    Example of request-level configuration:

    const common_args = {
        axios: {
            timeout: 30000
        }
    };
    
    b2.getBucket({ bucketName: 'my-bucket' }, common_args);
  2. Understand the B2 response object

    master

    Every request made through the B2 instance returns a response object containing the following fields:

    • status: int, the HTTP error status code.
    • statusText: the HTTP status text.
    • headers: the response headers.
    • config: the axios request configuration.
    • request: the axios request object.
    • data: the actual data returned from the Backblaze B2 API.
  3. Upgrade from 0.9.x to 1.0.x

    master

    The library switched its HTTP backend from request to axios. If you are upgrading from version 0.9.x, note the following breaking changes:

    1. Response Data Structure: The response data is no longer the root object in the promise resolution. You must now access it via res.data.
    2. Progress Reporting: The third parameter to .then() used for progress reporting in v0.9.12 has been removed. To report progress, you must now pass a callback function as an argument to the B2 method itself (e.g., b2.method(args, callback)).
    3. downloadFileById Signature: The method no longer accepts a fileId as the first parameter. It now expects a plain Object of arguments as the first parameter.
  4. Initialize the B2 client

    master

    To use the library, instantiate a new B2 object with your credentials. You can use either applicationKeyId and applicationKey or accountId and masterApplicationKey.

    By default, the client automatically retries requests. You can configure the global axios instance and the retry behavior during instantiation.

    const B2 = require('backblaze-b2');
    
    const b2 = new B2({
      applicationKeyId: 'applicationKeyId', // or accountId: 'accountId'
      applicationKey: 'applicationKey' // or masterApplicationKey
    });
  5. Perform multipart uploads for large files

    master

    For large files, split the file into parts (between 5MB and 5GB) and follow this workflow:

    1. Start: Call startLargeFile({ bucketId, fileName }) to get a fileId.
    2. Get Part URL: Call getUploadPartUrl({ fileId }) to get an uploadUrl and authorizationToken for a part.
    3. Upload Part: Call uploadPart({ partNumber, uploadUrl, uploadAuthToken, data }). You can run multiple uploadPart calls in parallel.
    4. Finish: Once all parts are uploaded, call finishLargeFile({ fileId, partSha1Array }) where partSha1Array is an array of SHA1 hashes for each part.

    Resuming interrupted uploads: If an upload fails, use listParts({ fileId, startPartNumber, maxPartCount }) to see which parts were successfully transmitted and resume from there.

    Tip: Check the recommendedPartSize returned by authorize() to determine the ideal part size.

    // 1. Start
    let response = await b2.startLargeFile({ bucketId, fileName });
    let fileId = response.data.fileId;
    
    // 2. Get URL for a part
    let partResponse = await b2.getUploadPartUrl({ fileId });
    let uploadURL = partResponse.data.uploadUrl;
    let authToken = partResponse.data.authorizationToken;
    
    // 3. Upload the part
    await b2.uploadPart({
        partNumber: 1,
        uploadUrl: uploadURL,
        uploadAuthToken: authToken,
        data: bufferPart
    });
    
    // 4. Finish
    await b2.finishLargeFile({
        fileId,
        partSha1Array: [sha1HashOfPart1, sha1HashOfPart2]
    });
  6. Upload a file

    master

    To upload a standard file, use uploadFile. Note that data must be a Buffer, not an encoded string.

    Arguments:

    • uploadUrl: The URL obtained from getUploadUrl().
    • uploadAuthToken: The token obtained from getUploadUrl().
    • fileName: The name of the file.
    • contentLength: (Optional) Data length. Defaults to data.byteLength.
    • mime: (Optional) Mime type. Defaults to b2/x-auto.
    • data: The file content as a Buffer.
    • hash: (Optional) SHA1 hash of the data.
    • info: (Optional) Object of key-value pairs for X-Bz-Info- headers. Max 10 keys. Keys must only contain a-z, A-Z, and -.
    • onUploadProgress: (Optional) Callback function for monitoring progress.
    b2.uploadFile({
        uploadUrl: 'uploadUrl',
        uploadAuthToken: 'uploadAuthToken',
        fileName: 'fileName',
        data: bufferContent,
        onUploadProgress: (event) => { /* handle progress */ }
    });
  7. Download files

    master

    You can download files either by their name or their unique fileId.

    • downloadFileByName({ bucketName, fileName, responseType, onDownloadProgress })
    • downloadFileById({ fileId, responseType, onDownloadProgress })

    Options:

    • responseType: Determines how the data is returned. Supported values (via axios): 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'.
    • onDownloadProgress: Callback for monitoring download progress.
  8. Manage Buckets

    master

    Use the following methods to manage your B2 buckets:

    • createBucket({ bucketName, bucketType }): Creates a new bucket. bucketType can be allPublic or allPrivate.
    • deleteBucket({ bucketId }): Deletes a bucket.
    • listBuckets(): Lists all buckets.
    • getBucket({ bucketName, bucketId }): Retrieves bucket information.
    • updateBucket({ bucketId, bucketType }): Updates bucket properties.
  9. Manage API Keys

    master

    Use these methods to manage application keys and their capabilities:

    • createKey({ capabilities, keyName, validDurationInSeconds, bucketId, namePrefix }): Creates a new key. capabilities is an array of strings (e.g., ['readFiles'] or b2.KEY_CAPABILITIES.READ_FILES).
    • deleteKey({ applicationKeyId }): Deletes a specific key.
    • listKeys({ maxKeyCount, startApplicationKeyId }): Lists available keys.
  10. Access B2 API action modules

    master

    The backblaze-b2 library organizes its API actions into four main modules. You can access these modules via the main entry point to perform operations related to authentication, bucket management, file manipulation, and key management.

    • auth: Handles authentication and session management.
    • bucket: Provides methods for managing B2 buckets.
    • file: Provides methods for uploading, downloading, and managing files.
    • key: Provides methods for managing API keys.
    const b2 = require('backblaze-b2');
    
    // Accessing the action modules
    const auth = b2.auth;
    const bucket = b2.bucket;
    const file = b2.file;
    const key = b2.key;
  11. Initialize the B2 client

    master

    The library exports the main B2 client functionality. To use it, require the module and instantiate the client. The client provides methods for interacting with the Backblaze B2 API, such as authentication, bucket management, and file operations.

    const B2 = require('backblaze-b2');
    const b2 = new B2({
      applicationKeyId: 'YOUR_KEY_ID',
      applicationKey: 'YOUR_APPLICATION_KEY'
    });