Search code examples
react-nativeshim

How to force TYPED_ARRAY_SUPPORT in buffer to false for react native?


I'm using a ton of packages that use node modules in React Native. I've managed to get them all functioning by shimming the key modules I need in before the other node modules load. The key module I shim in is buffer.

However, I've found a bit of a bug in buffer's code. Calling it a bug probably isn't appropriate since buffer was never meant to execute in the react native runtime.

When slicing, buffer checks to see if typed arrays are supported. If so then use the typedArray.subarray method to perform the slice. If not, perform our own slice manually.

This is illustrated with this code snippet

if (Buffer.TYPED_ARRAY_SUPPORT) {
    newBuf = Buffer._augment(this.subarray(start, end))
} else {
    var sliceLen = end - start
    newBuf = new Buffer(sliceLen, undefined)
    for (var i = 0; i < sliceLen; i++) {
        newBuf[i] = this[i + start]
    }
}

Problem is, typed arrays are not supported in react native. Somehow TYPED_ARRAY_SUPPORT is true at execution.

I've noticed that if, in the debugger I change TYPED_ARRAY_SUPPORT to true in the global namespace (Buffer.TYPED_ARRAY_SUPPORT is set according to the global.TYPED_ARRAY_SUPPORT definition) my code will execute beautifully.

How can I shim in global.TYPED_ARRAY_SUPPORT = false into the global namespace? For some reason my attempts to shim it in don't make it all the way to Buffer, while other modules being shimmed in do.


Solution

  • What I was trying to do with this to get around Buffer didn't end up working, but I did figure out how to inject TYPED_ARRAY_SUPPORT into the global namespace in case anyone needed to know.

    Simply put global.Buffer.TYPED_ARRAY_SUPPORT = false; in global.js and shim in your global.js as early in the app as possible to ensure it is executed before anything else.

    Here is a similar issue that expands on this procedure

    Can't find variable: Buffer