Skip to content

Commit

Permalink
fix: support use on Node.js 16 (#550)
Browse files Browse the repository at this point in the history
<!-- 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 -->
  • Loading branch information
fengmk2 authored Dec 2, 2024
1 parent e030ec9 commit 78e1336
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { LRU } from 'ylru';
import { patchForNode16 } from './utils.js';

patchForNode16();

import { HttpClient, HEADER_USER_AGENT } from './HttpClient.js';
import { RequestOptions, RequestURL } from './Request.js';

Expand Down
32 changes: 32 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { randomBytes, createHash } from 'node:crypto';
import { Readable } from 'node:stream';
import { performance } from 'node:perf_hooks';
import { ReadableStream } from 'node:stream/web';
import { Blob } from 'node:buffer';
import type { FixJSONCtlChars } from './Request.js';
import { SocketInfo } from './Response.js';
import symbols from './symbols.js';
Expand Down Expand Up @@ -205,3 +207,33 @@ export function convertHeader(headers: Headers): IncomingHttpHeaders {
}
return res;
}

// support require from Node.js 16
export function patchForNode16() {
if (typeof global.ReadableStream === 'undefined') {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.ReadableStream = ReadableStream;
}
if (typeof global.Blob === 'undefined') {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.Blob = Blob;
}
if (typeof global.DOMException === 'undefined') {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.DOMException = getDOMExceptionClass();
}
}

// https://github.com/jimmywarting/node-domexception/blob/main/index.js
function getDOMExceptionClass() {
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
atob(0);
} catch (err: any) {
return err.constructor;
}
}

0 comments on commit 78e1336

Please sign in to comment.