0

How do you get a Node.js Buffer from a Blob returned by the Node.js 18 Fetch API implementation?

I know I can get binary data in the form of a Blob using the Fetch API

const blob = await fetch("https://example.com/image.png")
    .then(r => r.blob())

but most libraries expect a Buffer. How do I get a buffer from fetch / convert a blob to a buffer?

Lumin
  • 373
  • 6
  • 21

2 Answers2

1

Instead of using fetch() to get a blob, you can get an arrayBuffer and then you can do Buffer.from(arrayBuffer) to convert it to a nodejs Buffer object. See doc.

const response = await fetch("https://example.com/image.png");
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

It is possible to convert response from fetch to Buffer using arrayBuffer and Buffer.from

function test() {
    fetch("https://example.com/image.png").then(async response =>{
        const buffer = Buffer.from(await response.arrayBuffer());
    });
}