encoding-transform.js
This file
Path
lib/transform/encoding-transform.js
53 lines · 1.6 KiB · JavaScript
Last changed by
Add more code comments (#984)ehmickybefore adoptionfdd8a9f
History of this fileTake it
Rename files (#977)ehmickybefore adoption4b2e316
lines 1–5why, one step back1import {Buffer} from 'node:buffer';2import {StringDecoder} from 'node:string_decoder';3import {isUint8Array, bufferToUint8Array} from '../utils/uint-array.js';45/*Add more code comments (#984)ehmickybefore adoptionfdd8a9f
line 6why, one step back6When using binary encodings, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.Rename files (#977)ehmickybefore adoption4b2e316
lines 7–53why, one step back7Chunks might be Buffer, Uint8Array or strings since:8- `subprocess.stdout|stderr` emits Buffers9- `subprocess.stdin.write()` accepts Buffer, Uint8Array or string10- Previous generators might return Uint8Array or string1112However, those are converted to Buffer:13- on writes: `Duplex.writable` `decodeStrings: true` default option14- on reads: `Duplex.readable` `readableEncoding: null` default option15*/16export const getEncodingTransformGenerator = (binary, encoding, skipped) => {17 if (skipped) {18 return;19 }2021 if (binary) {22 return {transform: encodingUint8ArrayGenerator.bind(undefined, new TextEncoder())};23 }2425 const stringDecoder = new StringDecoder(encoding);26 return {27 transform: encodingStringGenerator.bind(undefined, stringDecoder),28 final: encodingStringFinal.bind(undefined, stringDecoder),29 };30};3132const encodingUint8ArrayGenerator = function * (textEncoder, chunk) {33 if (Buffer.isBuffer(chunk)) {34 yield bufferToUint8Array(chunk);35 } else if (typeof chunk === 'string') {36 yield textEncoder.encode(chunk);37 } else {38 yield chunk;39 }40};4142const encodingStringGenerator = function * (stringDecoder, chunk) {43 yield Buffer.isBuffer(chunk) || isUint8Array(chunk)44 ? stringDecoder.write(chunk)45 : chunk;46};4748const encodingStringFinal = function * (stringDecoder) {49 const lastChunk = stringDecoder.end();50 if (lastChunk !== '') {51 yield lastChunk;52 }53};