blob to buffer in typescript

To convert a Blob to a Buffer in TypeScript, you can make use of the FileReader API. Here's an example code snippet to achieve that:

index.ts
function blobToBuffer(blob: Blob): Promise<Buffer> {
  return new Promise<Buffer>((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = () => {
      if (fileReader.result instanceof ArrayBuffer) {
        const buffer = Buffer.from(fileReader.result);
        resolve(buffer);
      } else {
        reject(new Error("Failed to convert Blob to Buffer."));
      }
    };
    fileReader.onerror = (error) => {
      reject(error);
    };
    fileReader.readAsArrayBuffer(blob);
  });
}

// Usage
const blob = new Blob(["Hello, World!"], { type: "text/plain" });
blobToBuffer(blob)
  .then((buffer) => {
    console.log(buffer); // Buffer object
  })
  .catch((error) => {
    console.error(error);
  });
738 chars
28 lines

In this code snippet, the blobToBuffer function takes a Blob object as input and returns a Promise that resolves to a Buffer object containing the blob data. The FileReader API is used to read the Blob content as an ArrayBuffer, which is then converted to a Buffer using the Buffer.from method.

Remember that this code is meant for use in environments where Buffer is available, such as Node.js. If you are working in a browser-based environment that does not have a native Buffer object, you may need to use alternative implementations or convert the ArrayBuffer to another data type that fits your requirements.

related categories

gistlibby LogSnag