0

I was wonder how to convert a base64 string to a base 64 url that you could use in the browser for my project. I've already tried using base64.toString('base64url'), but that didn't work. Below is some example code.

const fs=require("fs")

let base64image=fs.readFileSync("./image.png").toString("base64")
let base64txt=fs.readFileSync("./text.txt").toString("base64")

// converts base64 to a base 64 URL.
function toBase64URL(filetype, base64){ /* ... */ }

console.log(toBase64URL('png', base64image)) // => data:image/png;base64,iVBORw0KGgoAAAANSUhE...
console.log(toBase64URL('txt', base64txt)) // => data:text/plain;base64,dmVyeSBkZXRhaWxlZCA6KQ==
codingtuba
  • 366
  • 2
  • 13
  • You seem to mix up different things here. Base64Url is a variant of Base64 encoding. But what you show as the desired result (e.g. `data:image/png;base64,iVBORw0KG...`) has nothing to do with Base64Url encoding. It is a [Data-URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs) in which the data part is provided in form of a Base64 encoded string. There no magic involved, just identify the file type, create the first part (`data:image/png;base64,`) and concatenate the Base64 string. – jps May 24 '22 at 14:43

0 Answers0