Skip to content

Instantly share code, notes, and snippets.

@muety
Created March 6, 2017 09:36
Show Gist options
  • Save muety/3ef97aad64ac733831e41ef5025133e0 to your computer and use it in GitHub Desktop.
Save muety/3ef97aad64ac733831e41ef5025133e0 to your computer and use it in GitHub Desktop.
Get image as base64 string using node-fetch
'use strict';
const fetch = require('node-fetch')
, base64stream = require('base64-stream');
const URL = 'https://www.google.de/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
fetch(URL)
.then((res) => {
return new Promise((resolve, reject) => {
let chunks = [];
let myStream = res.body.pipe(base64stream.encode());
myStream.on('data', (chunk) => {
chunks = chunks.concat(chunk);
});
myStream.on('end', () => {
resolve(chunks.toString('base64'));
});
});
})
.then(console.log);
@drsmog
Copy link

drsmog commented Oct 23, 2021

@prionkor try like this

const { Base64Encode } = require("base64-stream");
const fetch = (...args) =>
  import("node-fetch").then(({ default: fetch }) => fetch(...args));

const getImageDataFromUrl = (url) => {
  return fetch(url).then((res) => {
    return new Promise((resolve, reject) => {
      let chunks = [];
      let myStream = res.body.pipe(new Base64Encode());
      myStream.on("data", (chunk) => {
        chunks = chunks.concat(chunk);
      });
      myStream.on("end", () => {
        resolve(chunks.toString("base64"));
      });
    });
  });
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment