• Beta

    Converts various data types to a Blob object, automatically detecting the data type or using the specified dataFormat to set the Blob's MIME type.

    This function supports plain text, JSON objects, binary data (Uint8Array, ArrayBuffer), and Blob inputs and will attempt to automatically detect the type of the data if dataFormat is not explicitly provided.

    Parameters

    • data: any

      The data to be converted into a Blob. This can be a string, an object, binary data (Uint8Array or ArrayBuffer), or a Blob.

    • Optional dataFormat: string

      An optional MIME type string that specifies the format of the data. Common types include 'text/plain' for string data, 'application/json' for JSON objects, and 'application/octet-stream' for binary data. If not provided, the function will attempt to detect the format based on the data type or default to 'application/octet-stream'.

    Returns {
        dataBlob: Blob;
        dataFormat: string;
    }

    An object containing the dataBlob, a Blob representation of the input data, and dataFormat, the MIME type of the data as determined by the function or specified by the caller.

    • dataBlob: Blob

      A Blob representation of the input data.

    • dataFormat: string

      The MIME type of the data.

    Example

    // Convert a JSON object to a Blob
    const { dataBlob, dataFormat } = dataToBlob({ key: 'value' }, 'application/json');

    // Convert a plain text string to a Blob without specifying dataFormat
    const { dataBlob: textBlob } = dataToBlob('Hello, world!');

    // Convert binary data to a Blob
    const binaryData = new Uint8Array([0, 1, 2, 3]);
    const { dataBlob: binaryBlob } = dataToBlob(binaryData);

    Throws

    An error if the data type is not supported or cannot be converted to a Blob.