Strip a UTF-8 byte order mark before parsing JSON files on desktop (#34504)

Co-authored-by: David Baker <dbkr@users.noreply.github.com>
This commit is contained in:
hayyaksi
2026-08-14 11:18:30 +00:00
committed by GitHub
parent 52c44ddbc5
commit 3773d662e4
2 changed files with 9 additions and 1 deletions
+7
View File
@@ -40,6 +40,7 @@ describe("loadJsonFile", () => {
vol.fromJSON({
"./file.json": JSON.stringify({ file1: true }),
"./nested/deep/file.json": JSON.stringify({ file2: true }),
"./bom.json": "\uFEFF" + JSON.stringify({ file3: true }),
});
});
@@ -54,6 +55,12 @@ describe("loadJsonFile", () => {
it("should return an empty object when file does not exist", () => {
expect(loadJsonFile("unknown-file.json")).toStrictEqual({});
});
it("should parse a file saved with a UTF-8 byte order mark", () => {
// Guard: the fixture really does start with a BOM, otherwise this test passes vacuously.
expect(memfs.readFileSync("bom.json", { encoding: "utf-8" })).toMatch(/^\uFEFF/);
expect(loadJsonFile("bom.json")).toStrictEqual({ file3: true });
});
});
describe("tryPaths", () => {
+2 -1
View File
@@ -40,7 +40,8 @@ export function loadJsonFile<T extends JsonDocument>(...paths: string[]): T {
return {} as T;
}
const file = fs.readFileSync(joinedPaths, { encoding: "utf-8" });
// Editors on Windows commonly save UTF-8 files with a byte order mark, which JSON.parse rejects.
const file = fs.readFileSync(joinedPaths, { encoding: "utf-8" }).replace(/^\uFEFF/, "");
return JSON.parse(file);
}