Skip to content
Myr

encoding-transform.js

This file

Path

lib/transform/encoding-transform.js

54 lines · 1.7 KiB · JavaScript

Last changed by

Rename files (#977)ehmickybefore adoption4b2e316

History of this file

Take it

Rename files (#977)ehmickybefore adoption4b2e316

lines 1–54why, one step back
1import {Buffer} from 'node:buffer';
2import {StringDecoder} from 'node:string_decoder';3import {isUint8Array, bufferToUint8Array} from '../utils/uint-array.js';45/*6When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.7This allows generator functions to operate with those types instead.8Chunks might be Buffer, Uint8Array or strings since:9- `subprocess.stdout|stderr` emits Buffers10- `subprocess.stdin.write()` accepts Buffer, Uint8Array or string11- Previous generators might return Uint8Array or string1213However, those are converted to Buffer:14- on writes: `Duplex.writable` `decodeStrings: true` default option15- on reads: `Duplex.readable` `readableEncoding: null` default option16*/17export const getEncodingTransformGenerator = (binary, encoding, skipped) => {18 if (skipped) {19 return;20 }2122 if (binary) {23 return {transform: encodingUint8ArrayGenerator.bind(undefined, new TextEncoder())};24 }2526 const stringDecoder = new StringDecoder(encoding);27 return {28 transform: encodingStringGenerator.bind(undefined, stringDecoder),29 final: encodingStringFinal.bind(undefined, stringDecoder),30 };31};3233const encodingUint8ArrayGenerator = function * (textEncoder, chunk) {34 if (Buffer.isBuffer(chunk)) {35 yield bufferToUint8Array(chunk);36 } else if (typeof chunk === 'string') {37 yield textEncoder.encode(chunk);38 } else {39 yield chunk;40 }41};4243const encodingStringGenerator = function * (stringDecoder, chunk) {44 yield Buffer.isBuffer(chunk) || isUint8Array(chunk)45 ? stringDecoder.write(chunk)46 : chunk;47};4849const encodingStringFinal = function * (stringDecoder) {50 const lastChunk = stringDecoder.end();51 if (lastChunk !== '') {52 yield lastChunk;53 }54};