tschaub / mock-fs

Configurable mock for the fs module
https://npmjs.org/package/mock-fs
Other
906 stars 86 forks source link

readFileSync with 'utf-8' option broken by node v20.5.0 #377

Open lg250137 opened 1 year ago

lg250137 commented 1 year ago

Node v20.5.0 introduced an optimization to fs.readFileSync for utf-8 files. Unfortunately, this breaks mock-fs. Here is a minimal test case that works with Node v20.4.0 but breaks with Node v20.5.0:

import mockFs from "mock-fs";
import { test } from "node:test";
import { readFileSync } from "fs";
import assert from "node:assert/strict";

test("mockFs", () => {
    mockFs({ "file": "contents" })
    const fileContents = readFileSync("file", 'utf-8').toString()
    assert.equal(fileContents, "contents")
})

In Node v20.5.0, I get the error Error: ENOENT: no such file or directory, open 'file'. The above test case also works in Node v20.5.0 if I remove the 'utf-8' option from readFileSync. This issue specifically occurs for readFileSync with 'utf-8' option.

Here is the relevant commit: https://github.com/nodejs/node/pull/48658

brendandburns commented 1 year ago

fwiw, anyone who hits this, you can replace fs.readFileSync(foo, 'utf-8') with fs.readFileSync(foo).toString('utf-8') and it will fix the mocking.

Of course you will lose the performance improvements in the nodejs change, so it's probably worth fixing mock-fs.

lg250137 commented 1 year ago

fwiw, anyone who hits this, you can replace fs.readFileSync(foo, 'utf-8') with fs.readFileSync(foo).toString('utf-8') and it will fix the mocking.

Of course you will lose the performance improvements in the nodejs change, so it's probably worth fixing mock-fs.

Unfortunately in my case I depend on a library that uses fs.readFileSync(foo, 'utf-8'), so I can't use that workaround.

marikaner commented 7 months ago

I guess this PR relates to this as well: https://github.com/tschaub/mock-fs/pull/381/files.