Skip to content

Commit 78e1336

Browse files
authored
fix: support use on Node.js 16 (#550)
<!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Enhanced compatibility with Node.js 16 through the addition of new utility functions. - Introduced global definitions for `ReadableStream`, `Blob`, and `DOMException` to support newer features. - **Bug Fixes** - Maintained error handling in JSON parsing to ensure detailed error messages. - **Documentation** - Updated comments and documentation to reflect new utility functions and their purposes. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent e030ec9 commit 78e1336

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/index.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
import { LRU } from 'ylru';
2+
import { patchForNode16 } from './utils.js';
3+
4+
patchForNode16();
5+
26
import { HttpClient, HEADER_USER_AGENT } from './HttpClient.js';
37
import { RequestOptions, RequestURL } from './Request.js';
48

src/utils.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { randomBytes, createHash } from 'node:crypto';
22
import { Readable } from 'node:stream';
33
import { performance } from 'node:perf_hooks';
4+
import { ReadableStream } from 'node:stream/web';
5+
import { Blob } from 'node:buffer';
46
import type { FixJSONCtlChars } from './Request.js';
57
import { SocketInfo } from './Response.js';
68
import symbols from './symbols.js';
@@ -205,3 +207,33 @@ export function convertHeader(headers: Headers): IncomingHttpHeaders {
205207
}
206208
return res;
207209
}
210+
211+
// support require from Node.js 16
212+
export function patchForNode16() {
213+
if (typeof global.ReadableStream === 'undefined') {
214+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
215+
// @ts-ignore
216+
global.ReadableStream = ReadableStream;
217+
}
218+
if (typeof global.Blob === 'undefined') {
219+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
220+
// @ts-ignore
221+
global.Blob = Blob;
222+
}
223+
if (typeof global.DOMException === 'undefined') {
224+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
225+
// @ts-ignore
226+
global.DOMException = getDOMExceptionClass();
227+
}
228+
}
229+
230+
// https://github.com/jimmywarting/node-domexception/blob/main/index.js
231+
function getDOMExceptionClass() {
232+
try {
233+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
234+
// @ts-ignore
235+
atob(0);
236+
} catch (err: any) {
237+
return err.constructor;
238+
}
239+
}

0 commit comments

Comments
 (0)