File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * This works the same as `Buffer.from(input).toString('base64')`
3+ * to work on both Node.js and browser environment.
4+ *
5+ * @internal
6+ *
7+ * @param input The string to encode to Base64.
8+ *
9+ * @returns Base64 encoded string.
10+ *
11+ * @see https://datatracker.ietf.org/doc/html/rfc4648
12+ *
13+ * @example const encodedHeader = toBase64(JSON.stringify(header));
14+ */
15+ export const toBase64 : ( input : string ) => string =
16+ typeof Buffer === 'undefined'
17+ ? ( input ) => {
18+ const utf8Bytes = new TextEncoder ( ) . encode ( input ) ;
19+ const binaryString = Array . from ( utf8Bytes , ( byte ) =>
20+ String . fromCodePoint ( byte )
21+ ) . join ( '' ) ;
22+ return btoa ( binaryString ) ;
23+ }
24+ : ( input ) => Buffer . from ( input ) . toString ( 'base64' ) ;
Original file line number Diff line number Diff line change 1+ import { toBase64 } from '../../internal/base64' ;
12import { deprecated } from '../../internal/deprecated' ;
23import { ModuleBase } from '../../internal/module-base' ;
34
@@ -388,8 +389,6 @@ export class ImageModule extends ModuleBase {
388389
389390 return type === 'svg-uri'
390391 ? `data:image/svg+xml;charset=UTF-8,${ encodeURIComponent ( svgString ) } `
391- : `data:image/svg+xml;base64,${ Buffer . from ( svgString ) . toString (
392- 'base64'
393- ) } `;
392+ : `data:image/svg+xml;base64,${ toBase64 ( svgString ) } ` ;
394393 }
395394}
Original file line number Diff line number Diff line change 1+ import { describe , expect , it } from 'vitest' ;
2+ import { faker } from '../../src' ;
3+ import { toBase64 } from '../../src/internal/base64' ;
4+
5+ // This test is kind of useless, because during testing the Buffer object is always available.
6+ describe ( 'toBase64' , ( ) => {
7+ it . each (
8+ faker . helpers . multiple (
9+ ( ) => faker . string . alphanumeric ( { length : { min : 0 , max : 100 } } ) ,
10+ { count : 5 }
11+ )
12+ ) (
13+ "should behave the same as `Buffer.from(value).toString('base64')`" ,
14+ ( value ) => {
15+ expect ( toBase64 ( value ) ) . toBe ( Buffer . from ( value ) . toString ( 'base64' ) ) ;
16+ }
17+ ) ;
18+ } ) ;
You can’t perform that action at this time.
0 commit comments