const fs = require('fs');

// function to encode file data to base64 encoded string
function base64Encode(file) {
  // read binary data
  const bitmap = fs.readFileSync('./imgs/sp.png');
  // convert binary data to base64 encoded string
  const bf = Buffer.alloc(bitmap.length, bitmap);
  return bf.toString('base64');
}

// function to create file from base64 encoded string
function base64Decode(base64str, file) {
  // create buffer object from base64 encoded string,
  // it is important to tell the constructor that the string is base64 encoded
  const bitmap = new Buffer(base64str, 'base64');
  // write buffer to file
  fs.writeFileSync(file, bitmap);
  console.log('******** File created from base64 encoded string ********');
}

function getDataUrl(filepath) {
  const str = base64Encode(filepath);
  let mime = '';
  if (filepath.indexOf('png') >= 0) {
    mime = 'image/png';
  }
  if (filepath.indexOf('jpg') >= 0 || filepath.indexOf('jpeg') >= 0) {
    mime = 'image/jpg';
  }
  if (filepath.indexOf('gif') >= 0) {
    mime = 'image/gif';
  }
  const dataurl = `data:${mime};base64,${str}`;
  return dataurl;
}

const str = getDataUrl('./imgs/sp.png');
console.log(str);
