Skip to content
Myr

encoding-transform.js

This file

Path

lib/stdio/encoding-transform.js

49 lines · 1.6 KiB · JavaScript

Last changed by

Rename 2 files with wrong file names (#865)ehmickybefore adoption4bd0fe3

History of this file

Take it

Rename 2 files with wrong file names (#865)ehmickybefore adoption4bd0fe3

lines 1–49why, one step back
1import {Buffer} from 'node:buffer';
2import {isUint8Array} from '../utils.js';34/*5When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.6This allows generator functions to operate with those types instead.7Chunks might be Buffer, Uint8Array or strings since:8- `childProcess.stdout|stderr` emits Buffers9- `childProcess.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 = encoding => {17 if (encoding === 'buffer') {18 return {transform: encodingBufferGenerator.bind(undefined, new TextEncoder())};19 }2021 const textDecoder = new TextDecoder();22 return {23 transform: encodingStringGenerator.bind(undefined, textDecoder),24 final: encodingStringFinal.bind(undefined, textDecoder),25 };26};2728const encodingBufferGenerator = function * (textEncoder, chunk) {29 if (Buffer.isBuffer(chunk)) {30 yield new Uint8Array(chunk);31 } else if (typeof chunk === 'string') {32 yield textEncoder.encode(chunk);33 } else {34 yield chunk;35 }36};3738const encodingStringGenerator = function * (textDecoder, chunk) {39 yield Buffer.isBuffer(chunk) || isUint8Array(chunk)40 ? textDecoder.decode(chunk, {stream: true})41 : chunk;42};4344const encodingStringFinal = function * (textDecoder) {45 const lastChunk = textDecoder.decode();46 if (lastChunk !== '') {47 yield lastChunk;48 }49};