Serve files from an in-memory file system with BrowserSync

319 Views Asked by At

I'm trying to figure out how to combine "memfs" with BrowserSync.

Is there a way to tell BrowserSync "Hey, don't work with Node's fs, but memfs's fs instead, which has a compatible API"

I can't use a solution that overrides fs globally (like mock-fs). I tried it and it works only for BrowserSync but I need Node's fs for other purposes.

import bs from 'browser-sync'
import mfs from "memfs"

bs.init({
    fsAPI: mfs.fs, // is there something like this?
    server: {
      baseDir: '/myDirFromMemFS'
    }
})
1

There are 1 best solutions below

0
UXK On BEST ANSWER

Problem solved. I understand that BrowserSync only works with fs. So I had no choice but to patch the fs globally in some way that would keep the original filesystem.

I leave here my solution in case someone comes with the same problem.

Using memfs + unionfs + fs-monkey

  • memfs to create the virtual volume.
  • unionfs to combine the virtual + real filesystem.
  • fs-monkey to monkey-patch the fs with the new virtual+real fs.

But there is a tricky part. Directly replacing real fs with something containing real fs will create a loop, so you need to do a shallow copy first as Szilveszter Safar comments on github (with a good code example)