| 41 | } |
| 42 | |
| 43 | export function fromBuffer( |
| 44 | buffer: Uint8Array, |
| 45 | encoding?: BufferEncoding | null |
| 46 | ): string { |
| 47 | if (encoding === "base64") { |
| 48 | if (typeof Buffer !== "undefined") { |
| 49 | return Buffer.from(buffer).toString("base64"); |
| 50 | } |
| 51 | const chunkSize = 65536; |
| 52 | let binary = ""; |
| 53 | for (let i = 0; i < buffer.length; i += chunkSize) { |
| 54 | const chunk = buffer.subarray(i, i + chunkSize); |
| 55 | binary += String.fromCharCode(...chunk); |
| 56 | } |
| 57 | return btoa(binary); |
| 58 | } |
| 59 | if (encoding === "hex") { |
| 60 | return Array.from(buffer) |
| 61 | .map((b) => b.toString(16).padStart(2, "0")) |
| 62 | .join(""); |
| 63 | } |
| 64 | if (encoding === "binary" || encoding === "latin1") { |
| 65 | if (typeof Buffer !== "undefined") { |
| 66 | return Buffer.from(buffer).toString(encoding); |
| 67 | } |
| 68 | const chunkSize = 65536; |
| 69 | if (buffer.length <= chunkSize) { |
| 70 | return String.fromCharCode(...buffer); |
| 71 | } |
| 72 | let result = ""; |
| 73 | for (let i = 0; i < buffer.length; i += chunkSize) { |
| 74 | const chunk = buffer.subarray(i, i + chunkSize); |
| 75 | result += String.fromCharCode(...chunk); |
| 76 | } |
| 77 | return result; |
| 78 | } |
| 79 | return textDecoder.decode(buffer); |
| 80 | } |
| 81 | |
| 82 | export function getEncoding( |
| 83 | options?: ReadFileOptions | WriteFileOptions | BufferEncoding | string | null |