diff --git a/src/index.ts b/src/index.ts index be405f6a5..b60e1c209 100644 --- a/src/index.ts +++ b/src/index.ts @@ -31,6 +31,7 @@ import BaseRequestHookEventFactory from './request-pipeline/request-hooks/events import BaseRequestPipelineContext from './request-pipeline/context/base'; import isRedirectStatusCode from './utils/is-redirect-status-code'; import * as contentTypeUtils from './utils/content-type'; +import { decodeBufferToString, encodeStringToBuffer } from './utils/encoding'; export default { Proxy, @@ -66,4 +67,6 @@ export default { ResponseInfo, isRedirectStatusCode, contentTypeUtils, + decodeBufferToString, + encodeStringToBuffer, }; diff --git a/src/utils/encoding.ts b/src/utils/encoding.ts new file mode 100644 index 000000000..09d41b305 --- /dev/null +++ b/src/utils/encoding.ts @@ -0,0 +1,17 @@ +import Charset from '../processing/encoding/charset'; +import charsetEncoder from 'iconv-lite'; + +export function decodeBufferToString (content: Buffer, contentType: string) { + const charset = new Charset(); + + charset.fromContentType(contentType); + + return charsetEncoder.decode(content, charset.get()); +} +export function encodeStringToBuffer (content: string, contentType: string) { + const charset = new Charset(); + + charset.fromContentType(contentType); + + return charsetEncoder.encode(content, charset.get()); +} diff --git a/ts-defs/index.d.ts b/ts-defs/index.d.ts index 5769c8032..3018bff90 100644 --- a/ts-defs/index.d.ts +++ b/ts-defs/index.d.ts @@ -619,6 +619,12 @@ declare module 'testcafe-hammerhead' { /** Proxy injectable scripts **/ export const INJECTABLE_SCRIPTS: string[]; + /** Extract String from Buffer **/ + export function decodeBufferToString (content: Buffer, contentType: string): string; + + /** Convert String to Buffer **/ + export function encodeStringToBuffer (content: string, contentType: string): Buffer; + /** Allows to accept cross-origin request for proxy routes **/ function acceptCrossOrigin (res: ServerResponse): void;