thecodrr / fdir

⚡ The fastest directory crawler & globbing library for NodeJS. Crawls 1m files in < 1s
https://thecodrr.github.io/fdir/
MIT License
1.46k stars 51 forks source link

Support Browser out of the box #97

Open jorenbroekema opened 2 months ago

jorenbroekema commented 2 months ago

Hi, I'm looking to perhaps migrate from glob to fdir and one big blocker for me is that glob allows you to inject a custom "fs" implementation like so:

// in-memory filesystem module, which works in the browser
import memfs from 'memfs';

glob('**/*.json', { fs: memfs });

It would be cool if the node builtin modules could be optionally substituted, e.g. path-unified is an NPM package which is just a node:path clone that works in the browser out of the box, and memfs would be a good node:fs replacement.

The path replacement is basically always a good idea because that module has no reason not to work in a browser env, the fs module is slightly harder because browser doesn't have filesystem access by default, you either need to use an in-memory replacement or an adapter which makes it interact with the browser's filesystem access API (bit more complicated). memfs allows doing both, fortunately.

You can use package entrypoints for example to internally do this in your package:

import fs from 'fdir/fs';

using:

{
  "exports": {
    "./fs": {
      "node": "./lib/fs-node.js", // re-exports "node:fs"
      "default": "./lib/fs-browser.js", // re-exports an empty variable "export let fs;"
    }
  }
}

so when not in a Node env, this lib would require the user to pass "fs" as an option to any fdir calls, similar to how you do it in glob, since there isn't a default fallback. You could also set a default fallback -> memfs instead of "empty variable", up to you.

If you're at all interested in this approach to make this lib work in browser out of the box without any bundler shenanigans, I'd be happy to investigate this and open a PR

thecodrr commented 2 months ago

This was planned but never got around to adding it. If someone can take it up, it should be a relatively simple change.

jorenbroekema commented 2 weeks ago

I've been desperately trying to get on this but I can't for the life of me find the time for it, summer's been a little crazy for me. Just FYI for transparency, it might be best if someone else pick this up😅 sorry