1

I want to read in a file, get it's size in bytes, and get its contents as a base64 string.

I was thinking to use the enclosed javascript functionality of karate, because it's so convenient.

I tried this:

 * def fileToAdd = 'test.pdf'
 * def fileToAddAsString = read(fileToAdd)
 * def fileToAddByteSize = (fileToAddAsString.length)
 * def fileToAddAsBase64 = (btoa(fileToAddAsString))

but the last line failed, as shown by the following output:

>>> failed features:
js failed:
>>>>
01: (btoa(fileToAddAsString))
<<<<
org.graalvm.polyglot.PolyglotException: ReferenceError: "btoa" is not defined
- <js>.:program(Unnamed:1)

Any ideas how to work-around this? I assume that the builtin javascript engine doesn't have the library that defines btoa(), but i don't know if that can be overcome, and if so, how.

Since my file is static, I could hardcode the base64 encoding of its contents, but I'd rather make it easier to change the file in the future, by having the code compute it for me, so i don't have to update the fileToAddAsBase64.

Please advise. Thanks!

Jon Detert
  • 51
  • 4
  • Is this in Node.js? If so, https://stackoverflow.com/questions/23097928/node-js-throws-btoa-is-not-defined-error – ceejayoz Apr 06 '23 at 21:26
  • 1
    This doesn't look like JavaScript. JavaScript declares variables with `var`, `let`, and `const`, not `def`. – Barmar Apr 06 '23 at 21:39
  • it's karate (https://github.com/karatelabs/karate), which has a javascript engine built into it, and karate's 'enclosed javascript' syntax. The read and the file size bits work fine. – Jon Detert Apr 06 '23 at 21:46
  • I think karate uses graalvm (https://www.graalvm.org/javascript/) – Jon Detert Apr 06 '23 at 21:48
  • 1
    Isn't Karate based on Java, not JavaScript ? – Spok Apr 06 '23 at 22:42
  • There is a compatibility table for each J's feature on https://developer.mozilla.org/en-US/docs/Web/API/btoa or you can use https://caniuse.com/?search=btoa – Konrad Apr 06 '23 at 23:01
  • @JonDetert the linked answer has all the details you need. the recommendation is that for this case (base64 encoding) just tap into the Java classes in the underlying JVM, it is pretty simple and you don't need to compile any java code – Peter Thomas Apr 07 '23 at 05:55

0 Answers0