OPFS database without a Worker #184
rhashimoto
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
A lot of people think that the OPFS API isn't supported outside of a dedicated Worker. That is only partially true. Per the specification, synchronous access handles to OPFS files are only available in a Worker, and they provide a simple, fast, and synchronous interface. However, before synchronous access handles existed, the spec contained other APIs for the same functionality. They are mostly asynchronous and generally slower, but they aren't restricted to a Worker context.
OPFS files can be read with a File interface (a subclass of Blob) and written with a FileSystemWritableFileStream interface. Reading with File is slower than an access handle, but only moderately slower - you might make up the performance by avoiding round-trip messaging with a Worker. Writing with FileSystemWritableFileStream, on the other hand, is horribly slow - you actually write to a temporary copy that is scanned for malware and then renamed to replace the original file. So even the smallest edit requires reading the entire file twice (once to copy, once for malware scan).
As painful as that sounds, it might be acceptable for applications where database access is exclusively or mostly read only. So I wrote yet another VFS, OPFSAnyContextVFS, that doesn't use synchronous access handles. It works!
Unfortunately, although it works on every kind of context, it doesn't completely work on every browser right now. Safari and Android Chrome don't support FileSystemWritableFileStream so write transactions won't work (read transactions should be fine).
Is this better than IDBBatchAtomicVFS (the other persistent VFS that works on all contexts)? For most purposes, no. It's slower. It can't write on some browsers. However, it is smaller and simpler, so you would have a better chance of debugging problems or adding features by yourself. It is also easier to import and export database files, because you can use the OPFS API directly or a general OPFS utility like this one. So its niche is applications that mostly (or exclusively) make read queries where it isn't convenient to use a Worker.
Beta Was this translation helpful? Give feedback.
All reactions