File size: 882 Bytes
2cae2a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * break a base64 string into sub-components
 */
export function extractBase64(base64: string = ""): {
  mimetype: string;
  extension: string;
  data: string;
  buffer: Buffer;
  blob: Blob;
} {
  // console.log(`extractBase64(${base64.slice(0, 120)})`)
  // Regular expression to extract the MIME type and the base64 data
  const matches = base64.match(/^data:([A-Za-z-+/]+);base64,(.+)$/)

  // console.log("matches:", matches)

  if (!matches || matches.length !== 3) {
    throw new Error("Invalid base64 string")
  }
   
  const mimetype = matches[1] || ""
  const data = matches[2] || ""
  const buffer = Buffer.from(data, "base64")
  const blob = new Blob([buffer])

  // this should be enough for most media formats (jpeg, png, webp, mp4)
  const extension = mimetype.split("/").pop() || ""

  return {
    mimetype,
    extension,
    data,
    buffer,
    blob,
  }
}