Skip to content
Myr

encoding-transform.js

This file

Path

lib/transform/encoding-transform.js

51 lines · 1.6 KiB · JavaScript

Last changed by

Allow passing `Buffer` to the `input` option (#1029)ehmickybefore adoption40fdc75

History of this file

Take it

Rename files (#977)ehmickybefore adoption4b2e316

lines 1–5why, one step back
1import {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 back
6When using binary encodings, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.

Rename files (#977)ehmickybefore adoption4b2e316

lines 7–42why, one step back
7Chunks 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) {

Allow passing `Buffer` to the `input` option (#1029)ehmickybefore adoption40fdc75

line 43why, one step back
43 yield isUint8Array(chunk) ? stringDecoder.write(chunk) : chunk;

Rename files (#977)ehmickybefore adoption4b2e316

lines 44–51why, one step back
44};
4546const encodingStringFinal = function * (stringDecoder) {47 const lastChunk = stringDecoder.end();48 if (lastChunk !== '') {49 yield lastChunk;50 }51};