I’m converting a Cordova app to Capacitor. I need to include various read-only data files for the app, like .sql files, HTML templates, etc. In Cordova, cordova.file.applicationDirectory refers to the www/ root directory, where read-only files can be included. In Capacitor, there seems to be no such directory that is readable by the app itself.
What’s the idiomatic way to include extra resources like this in a Capacitor app?
Turns out that in Capacitor, there’s no way to read these files directly from the filesystem, but you can fetch() them through the internal HTTP server if you know their URLs. This isn’t ideal, e.g. you can’t get the contents of a directory from Filesystem.readdir() or do most other file operations, but at least you can read the file.
If you’re using Vite like me, data files to include in your build go under the public/ directory under your top project root, or whatever you’ve set publicDir to in vite.config.js. (Note that what Vite calls “project root” is not what I’m calling “top project root” here; rather, Vite’s “project root” is what I would call the source “document root”, i.e. where it finds the starting index.html.)
In my project, I have directories full of HTML templates whose names could change from build to build, so I can’t predict their URLs. My solution will probably be to create a /manifest.json file at build time that lists all files under the document root. This isn’t perfect, so if you have any better ideas then please let me know, but for now I think this solution will do what I need.
It reads and copies files from the native app bundle at runtime, prepopulated databases, config files, any bundled asset. It also supports listing files in a directory, which solves the readdir() gap you ran into. Might save you the manifest.json workaround.
This is perfect, thank you! Yes, this does exactly what I need, and it’s less brittle than using a manifest. It could also solve another problem I’m having when fetch()ing assets through the internal web server. Thank you so much for your response!