Search code examples
react-nativereact-native-fs

React-Native: How to open locally bundled binary file


I'm writing a react-native app, and I want it to deploy with a zip file that contains a device firmware update.

Before letting the user send the update, I need my code to open the zip and do some validation of its contents.

I've found lots of zip-handling NPM packages, so all I need to do is load the file contents so I can feed it to one of these.

  • require('./firmware/fw.zip'); <-- packager doesn't include .zip by default
  • require('./firmware/fw.pdf'); <-- [gross hack] packager includes pdfs, but the actual result of the require() call is a number: 5. I don't know what I can do with this number to get file contents, but I'm pretty sure this require() system is designed for loading images, not binary data.
  • ReactNativeFs.openFile('./firmware/fw.zip'); <-- fails with ENOENT
  • ReactNativeFs.openFile(${ReactNativeFs.MainBundlePath}/firmware/fw.zip); <-- MainBundlePath is undefined on android.

This seems like a really basic question, so I'm sure I've missed a piece of documentation somewhere, but I'm heading into my third hour trying to load the contents of this file with no luck.

I'm pretty sure I could manually put the zip file into the appropriate android and ios resource directories, but that seems like a step down a hard-to-maintain road.


Solution

  • I encountered this problem again a couple months later (I'm apparently the only guy that needs to package .zips in react-native), and the above answer didn't work out for iOS. So I encoded the .zips as base64, put them in .js files, then used import to get the data from those .js files. This actually seems like a somewhat hacky but also flexible long-term solution, without having to mess around with platform-dependent file locations.

    See whole answer at my new question: React-native packager configuration - How to include .zip file in bundle?