Node.js Tutorial to Fetch Base64 Code of Local Image or Remote Image URL Using fetch-base64 Library in Javascript Full Project For Beginners

 

 

npm i fetch-base64

 

 

After installing it make an app.js file and copy paste the below code

 

 

app.js

 

 

const fetch = require('fetch-base64');

fetch.local('/path/to/image.jpg').then((data) => {
  // data[0] contains the raw base64-encoded jpg
}).catch((reason) => {});

fetch.remote('http://domain.com/to/image.jpg').then((data) => {
  // data[1] contains base64-encoded jpg with MimeType
}).catch((reason) => {});

fecth.auto('/remote/or/local/path/image.gif').then((data) => {

}).catch((reason) => {});

 

 

Examples

Include package

const fetch = require('fetch-base64');

Local

// will fetch image in /Users/bla/src/project/img/logo.jpg
const doFetchLocal = fetch.local('/Users/bla/src/project', './img/logo.jpg');
doFetchLocal.then((data) => {
  console.log(`base64 image raw: ${data[]}`);
}, (reason) => {
  console.log(`Fetch Failed: ${reason}`)
});

Remote

const doFetchRemote = fetch.remote('https://somedomain.com/image.jpg');
doFetchRemote.then((data) => {
  console.log(`base64 image with mimeType: ${data[1]}`);
}, (reason) => {
  console.log(`Fetch Failed: ${reason}`)
});
const doFetchRemote2 = fetch.remote('https://somedomain.com', '/image.jpg');
doFetchRemote2.then((data) => {
  console.log(`base64 image with mimeType: ${data[1]}`);
}, (reason) => {
  console.log(`Fetch Failed: ${reason}`)
});
const doFetchRemote = fetch.remote({ url: 'https://somedomain.com/image.jpg', headers: { 'custom-header': 'foo' } });
doFetchRemote.then((data) => {
  console.log(`base64 image with mimeType: ${data[1]}`);
}, (reason) => {
  console.log(`Fetch Failed: ${reason}`)
});

Auto

const doFetchAuto = fetch.auto('https://somedomain.com/image.jpg');
doFetchAuto.then((data) => {
  console.log(`base64 image: ${data[]}`);
}, (reason) => {
  console.log(`Fetch Failed: ${reason}`)
});
const doFetchAuto2 = fetch.auto('/some/local/', '/path/', './image.jpg');
doFetchAuto2.then((data) => {
  console.log(`base64 image: ${data[]}`);
}, (reason) => {
  console.log(`Fetch Failed: ${reason}`)
});

Leave a Reply