memory-fs
memory-fs copied to clipboard
Async methods in memory-fs don't work with `promisify` in native node module `util`
const { promisify } = require('util')
const fs = require('fs')
promisify(fs.readFile)('/hello.txt', 'utf-8') // work well
.then(console.log.bind(console))
.catch(console.log.bind(console))
// but...when I use `memory-fs` in my project...
const MemoryFileSystem = require('memory-fs')
const fs = new MemoryFileSystem()
promisify(fs.readFile)('/hello.txt', 'utf-8') // dose not work
.then(console.log.bind(console))
.catch(console.log.bind(console))
// I need write this way `promisify(fs.readFile.bind(fs))` to make it work well,
// I think `memory-fs` should do this for users. is this an issue ?
It's because of how MemoryFileSystem is a class. It doesn't really need to be - I might fork this if they don't intend to fix this, because it's kind of annoying. Native fs doesn't need bind, this package should work the same so that it's a drop in replacement and you don't have to change your client code.
In the past, I worked around this by creating what I've been calling a "bound proxy".
const fs = new Proxy(
new MemoryFileSystem(),
{
get(obj, prop) {
if (typeof obj[prop] === 'function') {
return obj[prop].bind(obj);
}
return obj[prop]
}
}
);