Search code examples
javascriptobjective-cmacosstdjavascript-automation

How do I get to see the contents of a NSData array in JXA?


I need to do some manipulation on a file byte array and as far as I have read, I cannot do this unless I use ObjectiveC bridging. This is what I have done for now:

var filepath = file.toString();
ObjC.import('stdlib');
ObjC.import('Foundation');

var theFileData = $.NSData.dataWithContentsOfFile(filepath);
var fileSize = theFileData.length;

If I try using $.malloc(filesize) it will say the function is undefined... how am I supposed to check the contents of theFileData ?


Solution

  • I have gone into this in-depth in the answer I posted to your other question, so please refer to that for more details.

    But here you go:

    function readBytes(filepath) {
        const bytes    = $.NSData.dataWithContentsOfFile(
                            $.NSString.stringWithString(filepath)
                             .stringByStandardizingPath);
        const bytesPtr = bytes.bytes;
        var   bytesArr = [];
        const numBytes = Number(bytes.length);
    
        for (let i = 0; i < numBytes; i++) {
            bytesArr.push(bytesPtr[i]);
        }
    
        return bytesArr;    
    }