How to base64 encode a string

Hi,
I am writting helper cli utility for myself. I need to write a function base64 :: String -> String. It simply base64 encodes a string. Both input output should be strings no ArrayBuffers or anything.

First I tried to use

import Data.ArrayBuffer.ArrayBuffer as AB
import Data.Base64 (encodeBase64, runBase64)

base64 :: String -> String
base64 = AB.fromString >>> encodeBase64 >>> runBase64

but purescript-base64-codec does not seems to be in latest package set (I am using spago).

Looking for alternative I wanted to do purescript alternative of

Buffer.from("Hello World").toString('base64')

but Node.Buffer.fromString here returns Effect String. I could rewrite my code so that I can use that but there just has to be way how to implement that base64 function as pure.

Thanks for your ideas!

This looks relevant purescript-base64-2 - Pursuit
although I see it also is not in the latest package set: https://github.com/purescript/package-sets/blob/master/packages.json

I believe this is effectful because the underlying buffer is mutable. But if you’re doing this in one fell swoop, it doesn’t need to be in Effect. In that situation, it’s more like ST where the side effects are local to a given scope and the mutability doesn’t leak outside of that scope.

If I needed this badly, I would just write some FFI, type it as not effectful, and call it a day

1 Like

Have you tried this package too? I think the package simply wraps the javascript atob and btoa functions. Anyway, it looks like b64 is included in the current packagesets if I’m not mistaken.

https://pursuit.purescript.org/packages/purescript-b64/0.0.8/docs/Data.String.Base64

1 Like

@leobm That is exactly what I wanted! How come I missed it while searching. Thanks

Thanks for all reactions.

Case closed