jvilk / BrowserFS

BrowserFS is an in-browser filesystem that emulates the Node JS filesystem API and supports storing and retrieving files from various backends.
Other
3.06k stars 216 forks source link

Update backend creation, remove monkey patching. #372

Closed james-pre closed 9 months ago

james-pre commented 9 months ago

At first, BFS used callbacks in the constructor. As that was odd behavior, backend creation was changed to be done with the static Create method. Now that BFS uses promises internally, it would be better to use a more straightforward approach using a public constructor:

abstract class Backend implements FileSystem {
    abstract whenReady(): Promise<this>;
}

class ExampleSyncBackend extends Backend {
    async whenReady() {
        return this;
    }
}

class ExampleAsyncBackend extends Backend {
    private _ready: Promise;
    constructor(options){
        this._ready = this._initialize(options);
    }

    private async _initialize(options): Promise<this> {
        // async initialization using options
    }

    async whenReady() {
        return this_ready;
    }
}

This allows users to use backends without a callback:

backend:

async op() {
    await this.whenReady();
    ...
}

user code (remember this is through the compatibility layer):

configure({ fs: 'ExampleAsyncBackend' }); // note that await is not used.
const fs = BFSRequire('fs');
fs.op(() => {
    // no waiting for the FS to be ready!
});
james-pre commented 9 months ago

Resolved in 8706f3d