fs-require
Create a require()
function from any file-system.
Features
- 💞 Works well with memfs!
- 🪄 Resolves implicit entry
index
and implicit extensions js
and json
- 🗺 Resolves relative and absolute paths
- 📍
__dirname
& __filename
- 👻 Mocks
fs
within fsRequire - 👣 Call stack shows paths with
fs-require://
protocol
🙋♀️ Why?
Using fs-require with memfs is a great combination for writing tests that interact with the file-system.
Testing functionality that interacts with the file-system can be brittle because they expect a clean slate and can also be dangerous if the path is wrong. Creating a virtual file-system with memfs
and testing its contents with fsRequire
makes it secure and fast!
👨🏫 Usage
import { Volume } from 'memfs'
import { createFsRequire } from 'fs-require'
const virtualFs = Volume.fromJSON({
'/hello-world.js': `
module.exports = function () {
return 'Hello world!'
}
`
})
const fsRequire = createFsRequire(virtualFs)
const helloWorld = fsRequire('/hello-world')
console.log(helloWorld())
👨👩👧 Related
- fs-monkey - By the same author of memfs. Patches the global
require
to access a virtual fs.