Skip to content

Commit

Permalink
Only polyfill fetch for file: URLs on Node.
Browse files Browse the repository at this point in the history
There are some cases where one might want to load a bundle from network
on Node, like in the VS Code extension host (at a future point, when
VS Code updates the Node version to v20.x or later and the extension
switches to using proper async imports instead of the awful hack it is
currently doing).
  • Loading branch information
whitequark committed Jan 7, 2024
1 parent 66ac805 commit f42d61d
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions lib/fetch.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
// Node v18.x doesn't have a usable `fetch()`.
let fetch = globalThis.fetch;
let fetch;
if (typeof process === 'object' && process.release?.name === 'node') {
fetch = async function(url) {
const { readFile } = await import('fs/promises');
let contentType = 'application/octet-stream';
if (url.pathname.endsWith('.wasm'))
contentType = 'application/wasm';
return new Response(await readFile(url), { headers: { "Content-Type": contentType } });
// Node doesn't have a usable `fetch()`.
fetch = async function(url, options) {
if (url.protocol === 'file:') {
const { readFile } = await import('fs/promises');
let contentType = 'application/octet-stream';
if (url.pathname.endsWith('.wasm'))
contentType = 'application/wasm';
return new Response(await readFile(url), { headers: { "Content-Type": contentType } });
} else {
return globalThis.fetch(url, options);
}
};
} else {
fetch = globalThis.fetch;
}

export default fetch;

0 comments on commit f42d61d

Please sign in to comment.