encoding-end.js
This file
Path
lib/stdio/encoding-end.js
49 lines · 1.6 KiB · JavaScript
Last changed by
Split files (#837)ehmickybefore adoption672c2d7
History of this fileTake it
Split files (#837)ehmickybefore adoption672c2d7
lines 1–49why, one step back1import {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 getEncodingStartGenerator = encoding => {17 if (encoding === 'buffer') {18 return {transform: encodingStartBufferGenerator.bind(undefined, new TextEncoder())};19 }2021 const textDecoder = new TextDecoder();22 return {23 transform: encodingStartStringGenerator.bind(undefined, textDecoder),24 final: encodingStartStringFinal.bind(undefined, textDecoder),25 };26};2728const encodingStartBufferGenerator = 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 encodingStartStringGenerator = function * (textDecoder, chunk) {39 yield Buffer.isBuffer(chunk) || isUint8Array(chunk)40 ? textDecoder.decode(chunk, {stream: true})41 : chunk;42};4344const encodingStartStringFinal = function * (textDecoder) {45 const lastChunk = textDecoder.decode();46 if (lastChunk !== '') {47 yield lastChunk;48 }49};