memory-fs icon indicating copy to clipboard operation
memory-fs copied to clipboard

Async methods in memory-fs don't work with `promisify` in native node module `util`

Open Jocs opened this issue 8 years ago • 2 comments

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 ?

Jocs avatar Oct 24 '17 16:10 Jocs

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.

nrkn avatar Nov 14 '17 05:11 nrkn

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]
    }
  }
);

GeorgeTaveras1231 avatar Oct 16 '18 13:10 GeorgeTaveras1231