DEV Community

Jeon
Jeon

Posted on

Read Text Asset File in Expo

§ Install expo-asset and expo-file-system:

npx expo install expo-asset expo-file-system
Enter fullscreen mode Exit fullscreen mode

§ Add expo-asset plugin in app.config.js (or in app.json), if it has not been added by the previous step:

   plugins: [
+    "expo-asset"
   ]
Enter fullscreen mode Exit fullscreen mode

§ Install @expo/metro-config:

npm install --save-dev @expo/metro-config 
Enter fullscreen mode Exit fullscreen mode

§ Create metro.config.js:

 const {  getDefaultConfig } = require("expo/metro-config");

 const config = getDefaultConfig(__dirname);
+config.resolver.assetExts.push("txt");

 module.exports = config;
Enter fullscreen mode Exit fullscreen mode

§ Create or put a text file under /assets folder

§ Code:

async function readTextAsset() {
  try {
    const nodeRequire = require("@/assets/filename.txt");
    const asset = Asset.fromModule(nodeRequire);
    await asset.downloadAsync();
    if (asset.localUri) {
      const fileContents = await readAsStringAsync(asset.localUri);
      // Do something with `fileContents`
    }
  } catch (error) {
    console.error(error);
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)