I have a set of bytes in an ArrayBuffer. I need to base64 encode this in k6. How do I accomplish this?
In node.js it is data.toString(‘base64’)
in browsers the btoa() function seems to be the way to go.
Neither of these works in k6, or I did not manage to get them to work.
There is the k6 encoding module, which can do encoding.b64encode(string)
But I do not see how to use this on an array of bytes, it seems to only take a string. And what I need to do is to encode an array of bytes.
I tried to encode the string first with String.fromCharCode.apply(null, new Uint8Array(str)) but it does not seem to produce correct result if I encode this with k6.encode.
I also simply tried to do encoding.b64encode(new Uint8Array(typedArray)); but in this case, also the Go implementation throws an error about not being able to convert the Uint8Array to an array of uint8 in Go…
Up until recently, ArrayBuffer support in k6 was through a polyfill, so we couldn’t easily support it in the encoding.b64encode() function. Now it’s handled natively though the goja JS runtime we use, so we should be able to do it without a lot of fuss. I’ve added a note about it in Better support for binary data · Issue #1020 · grafana/k6 · GitHub
var str = "testing"; // just for illustrative purposes, base64ArrayBuffer() seems to work for non-ASCII values as well
var buffer = new ArrayBuffer(str.length);
var typedArr = new Uint8Array(buffer);
for (var i = 0; i < str.length; i++) {
typedArr[i] = str.charCodeAt(i);
}
console.log(typedArr);
console.log(base64ArrayBuffer(buffer));
Thanks for your reply. I tried this same approach, it does not seem to work so well when your data is pure binary and not a string such as “testing”. But binary with any values from 0-255 in each byte.
I found this works (so far at least):
But would definitely be nice to have support in the encoding module itself.
Ah yes, I see you are actually referencing the same code, was just confusing it with some other links online where they use the charAtcode . Yes, it a good approach