React-Native: How to open locally bundled binary file

一曲冷凌霜 提交于 2019-12-10 18:27:22

问题


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.


回答1:


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?




回答2:


Partial solution:

Modify android/app/build.gradle, and add

task copyData(type: Copy) {
    from '../../firmware/fw.zip'
    into 'src/main/assets/raw/firmware'
}
preBuild.dependsOn copyData

This will at least ensure that the file gets copied each time you build, and is then available with ReactNativeFs.readFileAssets('raw/firmware/fw.zip', 'base64'). I'm not entirely thrilled because I still have to have iOS/android dependent code when loading the file, but at least it's loading now.

Tip: watch out for your syntax in gradle. into src/main/assets/myFirmware.zip will create a DIRECTORY called myFirmware.zip, and put your zip file underneath it. Then readFileAssets will still fail because it's finding a directory at your path, not a file.



来源:https://stackoverflow.com/questions/50492089/react-native-how-to-open-locally-bundled-binary-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!