Categories
JavaScript Answers

How to get image from web and encode with base64 with Node.js?

Spread the love

To get image from web and encode with base64 with Node.js, we call the axios.get method.

For instance, we write

const axios = require("axios");
//...
const image = await axios.get(url, { responseType: "arraybuffer" });
const raw = Buffer.from(image.data).toString("base64");
const base64Image = "data:" + image.headers["content-type"] + ";base64," + raw;

to call axios.get to get the image from url with a get request.

We get the response as an arraybuffer with { responseType: "arraybuffer" }.

Then we call Buffer.from to convert the arraybuffer to a buffer.

And we call toString with 'base64' to convert it to a base64 string.

Then we put the content type string before the string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *