android – In React Native how do you bundle a text file and read it's value at runtime?-ThrowExceptions

Exception or error:

A few reasons why I might do this:

  • To create some webviews and inject javascript loaded from files
  • To separate large chunks of text into separate files rather than forcing them into views
  • To include raw data of an arbitrary format (eg, CSV) to be used in the app

In React Native you can use require to import an image file, but as far as I’ve seen, this only works for image files. And it (strangely) also works for JSON files (see Importing Text from local json file in React native). However, I haven’t seen anywhere talking about importing plain old text files.

How to solve:

After looking and asking around, the best I can come up with is to use a
fork of the react-native-fs library to access android “assets”. This fork is a pull request out and as soon as it gets merged you can use it.

Note that in android dev, “assets” specifically refer to accessing the raw contents of a file. In order to do this sort of thing on the react native side, you need to write a native module to interface with react, hence the library above. See here (and search for assets).

In your react native project, make a file called something like android/app/src/main/assets/text.txt. Using the version of react-native-fs mentioned above, you do:

RNFS.readFileAssets('test.txt').then((res) => {
  console.log('read file res: ', res);
})

update: If you want the pull request that would enable this ability to go through, you should go let the author know you want it by giving it a thumbs up on github.

###

There is a library that solves this exact problem: React-Native-Local-Resource. The library allows you to asynchronously load any type of text file in Android and iOS at runtime.

###

Here’s how I did it synchronously in Swift and JS for iOS/tvOS/macOS, based on the React Native docs: Exporting Constants.

  • Disadvantage: Note that the file will be loaded into memory once upon startup, and won’t be dynamically re-loadable.

  • Advantage: It’s synchronous, simple, and works at run-time whether in native or JS.

MyJSFile.js

import { NativeModules } from "react-native";

console.log(NativeModules.MyNativeModule.MyFileContents);

We import our native module and access the MyFileContents constant that we expose upon it. It works synchronously with no bridge-crossing (as far as I understand, it’s injected into the React Native JSContext via JavaScriptCore).

In Build Phases, ensure that this file is added into Copy Bundle Resources. Otherwise your app will quickly crash upon trying to read it.

MyNativeModule.swift

import Foundation

@objc(MyNativeModule)
class MyNativeModule: RCTEventEmitter {
    @objc override func constantsToExport() -> [AnyHashable : Any]! {
        let contents: String = try! String(contentsOfFile: Bundle.main.path(forResource: "MyFile.min", ofType: "js")!)
        return [
            "MyFileContents": contents
        ]
    }
    @objc override func supportedEvents() -> [String]! {
        return []
    }
    @objc override static func requiresMainQueueSetup() -> Bool {
        return false
    }
}

One can likely make a simpler/slimmer native module than this one (by subclassing something with less functionality than RCTEventEmitter), but this is the file I had lying around to work with, so here it is.

MyProject-Bridging-Header.h

#import <React/RCTBridge.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTUIManager.h>
#import <React/RCTEventEmitter.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTJavaScriptLoader.h>
#import <React/RCTLinkingManager.h>
#import <React/RCTRootView.h>
#import <React/RCTEventDispatcher.h>

Here’s the bridging header I’m using. It exposes a lot more headers than are strictly necessary, but you may need them for other native modules later anyway.

As this approach uses Swift, make sure to enter your Build Settings and set Always Embed Swift Standard Libraries to Yes if you haven’t already. And if this is the first time building your app with Swift embedded, you may want to clear DerivedData for luck before building.

… Or simply rewrite that same Swift code in Obj-C, as the documentation shows how.

Leave a Reply

Your email address will not be published. Required fields are marked *