0

I am using the LoadBytes function from P5.JS which returns an object but I am unable to access "object" via using ".bytes" or "['bytes']".

For some reason when running a live server it seems to work perfectly.

function get_rom () {
    var fileList = document.getElementById("rom").files;
    var fileReader = new FileReader();
    
    if (fileReader && fileList && fileList.length) {
        url = URL.createObjectURL(fileList[0])
        return loadBytes(url)
    }
}

function loadarom () {
    object = get_rom()
    
    print(object.bytes[1]) // <-- issue here
}
AGE
  • 3,752
  • 3
  • 38
  • 60
  • 1
    If your server is not running then you should expect no data to be returned from `loadBytes` ... you need to ensure that you throw an error accordingly or have a conditional statement to access the object structure only when it is not undefined – AGE Jun 17 '21 at 14:58

2 Answers2

0

When using loadBytes() the returned object will not immediately have the bytes array populated. You need to use the callback parameter to loadBytes():

let loadBtn;

function setup() {
    noCanvas();
    noLoop();

    loadBtn = createButton("Load Rom");
    loadBtn.mousePressed(loadarom);
}

function get_rom(onSuccess) {
    let fileList = document.getElementById("rom").files;
    // Alternate method using FileReader has been commented out
    // let fileReader = new FileReader();
    
    /*
    fileReader.addEventListener("load", function () {
    // convert image file to base64 string
    loadBytes(fileReader.result, onSuccess);
  }); */

    if (fileList && fileList.length) {
        loadBytes(URL.createObjectURL(fileList[0]), onSuccess);
        // fileReader.readAsDataURL(fileList[0]);
    }
}

function loadarom() {
    get_rom(obj => {
        print(obj.bytes[0]);
    })
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.js"></script>
</head>

<body>
    <input id="rom" type="file" />
</body>

</html>
Paul Wheeler
  • 18,988
  • 3
  • 28
  • 41
0

Barley don't need p5.js for such a easy task.
use blob.arrayBuffer()

<script type="module">

var file = new File(['abc'], 'abc.txt')
var bytes = new Uint8Array(await file.arrayBuffer())
console.log(bytes)

</script>
(SO! You should support top level await in a async IIFE fn or start adding type="module" to js-code
Endless
  • 34,080
  • 13
  • 108
  • 131