Skip to content

Only works the first time #254

Closed
@bard

Description

@bard

Shown with promises and async/await for clarity. The issue doesn't change with nested callbacks, and makes it impossible to use mock-fs in automated tests.

const mockfs = require('mock-fs')
const fs = require('fs')
const util = require('util')
const readFileAsync = util.promisify(fs.readFile)

const test = async () => {
  try {
    mockfs({ foo: 'bar' })
    console.log('first run:', await readFileAsync('foo', 'utf8'))
    mockfs.restore()

    mockfs({ foo: 'bar' })
    console.log('second run', await readFileAsync('foo', 'utf8'))
    mockfs.restore()
  } catch (err) {
    console.error(err)
  }
}

test()

Output:

first run: bar
{ Error: EBADF, bad file descriptor
    at Binding._getDescriptorById (/tmp/test/node_modules/mock-fs/lib/binding.js:231:11)
    at Binding.<anonymous> (/tmp/test/node_modules/mock-fs/lib/binding.js:501:27)
    at maybeCallback (/tmp/test/node_modules/mock-fs/lib/binding.js:49:18)
    at Binding.read (/tmp/test/node_modules/mock-fs/lib/binding.js:500:10)
    at ReadFileContext.read (internal/fs/read_file_context.js:88:5)
    at FSReqWrap.readFileAfterStat [as oncomplete] (fs.js:271:11)
    at /tmp/test/node_modules/mock-fs/lib/binding.js:94:16
    at /tmp/test/node_modules/mock-fs/lib/binding.js:57:9
    at process._tickCallback (internal/process/next_tick.js:61:11)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
  message: 'EBADF, bad file descriptor',
  code: 'EBADF',
  errno: 9 }

Environment:

$ node -v
v10.10.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions