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

Sometimes, we want to get image from web and encode with base64 with Node.js.

In this article, we’ll look at how to get image from web and encode with base64 with Node.js.

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

To get image from web and encode with base64 with Node.js, we can use the http.get method.

For instance, we write

const http = require('http');

http.get('https://picsum.photos/200/300', (resp) => {
  resp.setEncoding('base64');
  let body = `data:${resp.headers["content-type"]};base64,`;

  resp.on('data', (data) => {
    body += data
  });
  resp.on('end', () => {
    console.log(body);
  });
}).on('error', (e) => {
  console.log(`Got error: ${e.message}`);
});

to define the body in the http.get callback.

We call resp.on with 'data' to listen for the data event which has the response chunks in the data parameter of the data event callback.

We concatenate that to body and then we can get the whole response from the end event callback, which is

resp.on('end', () => {
  console.log(body);
});

Conclusion

To get image from web and encode with base64 with Node.js, we can use the http.get method.