Search code examples
javascriptjavanashorn

Converting byte[] to ArrayBuffer in Nashorn


How do I convert an array of bytes into ArrayBuffer in Nashorn? I am trying to insert binary data into a pure JavaScript environment (i.e., it doesn't have access to Java.from or Java.to) and so would like to create an instance out an array of bytes.


Solution

  • Looks like I was going about this the wrong way. It made more sense to convert it into Uint8Array since what I'm sending in is an array of bytes.

    I created the following function:

    function byteToUint8Array(byteArray) {
        var uint8Array = new Uint8Array(byteArray.length);
        for(var i = 0; i < uint8Array.length; i++) {
            uint8Array[i] = byteArray[i];
        }
    
        return uint8Array;
    }
    

    This will convert an array of bytes (so byteArray is actually of type byte[]) into a Uint8Array.