var fs = require('fs');

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

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

function getDataUrl(filepath){
    var str=base64_encode(filepath);
    var 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";
    }
    var dataurl=`data:${mime};base64,`+str;
    return dataurl;
}

var str=getDataUrl("./imgs/sp.png");
console.log(str);