Skip to content

Commit 5415506

Browse files
committed
refactor: update file loading mechanism to use fetchFile function
fixes: - YSON being broken in browsers due to node:fs/promises import - absolute paths in node.js failing as fetching file:// urls aren't supported (yet)
1 parent 0e583f1 commit 5415506

1 file changed

Lines changed: 26 additions & 13 deletions

File tree

src/YSON.ts

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
import { defaultRevivers } from "./defaultRevivers.js"
2-
import fs from "fs/promises"
32
import { parseValue } from "./parse.js"
43
import { stringifyValue } from "./stringify.js"
54
import { ParseOptions, StringifyOptions, YSONParseType, YSONValue } from "./types.js"
65
import YSONSyntaxError from "./YSONSyntaxError.js"
76

7+
let fs: any = null
8+
9+
if (typeof window === "undefined") {
10+
fs = (await import("node:fs/promises")).default
11+
}
12+
813
/**
914
* YSON - Parse, Stringify, Load
1015
* @module
@@ -49,6 +54,15 @@ export default class YSON {
4954

5055
/**
5156
* Loads and parses raw YSON strings from an URL
57+
*
58+
* In browser contexts,
59+
* - http(s):// urls are fetched over the network,
60+
* - paths are resolved relative to the current page and fetched over the network.
61+
*
62+
* In node (deno, ...) contexts,
63+
* - http(s):// urls are fetched over the network,
64+
* - paths are resolved relative to the current working directory and read from the filesystem,
65+
* - and file:// urls are read from the filesystem.
5266
* @param source URL or local path to source .yson file
5367
* @param types types to recognise and parse (optional)
5468
* @param options (reserved for future use) (optional)
@@ -61,25 +75,24 @@ export default class YSON {
6175
if ("location" in globalThis) {
6276
baseUrl = location.href
6377
if (!baseUrl.endsWith("/")) baseUrl += "/"
64-
} else if (source.startsWith("./") || source.startsWith("../")) {
65-
const raw = await fs.readFile(source, { encoding: "utf-8" })
66-
return YSON.parse(raw, types, options)
6778
} else {
6879
baseUrl = `file://${process.cwd()}/`
6980
}
7081

71-
if (source.startsWith("./")) {
72-
source = `${baseUrl}${source.substring(2)}`
73-
} else if (source.startsWith("../")) {
74-
source = `${baseUrl}${source}`
75-
} else {
76-
source = new URL(source)
77-
}
82+
source = new URL(source, baseUrl)
7883
}
7984

80-
const res = await fetch(source)
81-
const raw = await res.text()
85+
const raw = await fetchFile(source)
8286
return YSON.parse(raw, types, options)
8387
}
8488

8589
}
90+
91+
async function fetchFile(url: URL): Promise<string> {
92+
if (url.protocol == "file:" && !("location" in globalThis)) {
93+
return await fs.readFile(url.pathname, "utf-8")
94+
}
95+
96+
const res = await fetch(url)
97+
return await res.text()
98+
}

0 commit comments

Comments
 (0)