encoding-start.js
This file
Path
lib/stdio/encoding-start.js
55 lines · 1.8 KiB · JavaScript
Last changed by
Split files (#837)ehmickybefore adoption672c2d7
History of this fileTake it
Split files (#837)ehmickybefore adoption672c2d7
lines 1–55why, one step back1import {StringDecoder} from 'node:string_decoder';2import {isUint8Array} from '../utils.js';3import {willPipeStreams} from './forward.js';45// Apply the `encoding` option using an implicit generator.6// This encodes the final output of `stdout`/`stderr`.7export const handleStreamsEncoding = (stdioStreams, {encoding}, isSync) => {8 const newStdioStreams = stdioStreams.map(stdioStream => ({...stdioStream, encoding}));9 if (!shouldEncodeOutput(newStdioStreams, encoding, isSync)) {10 return newStdioStreams;11 }1213 const objectMode = newStdioStreams.findLast(({type}) => type === 'generator')?.value.objectMode === true;14 const stringDecoder = new StringDecoder(encoding);15 const generator = objectMode16 ? {17 transform: encodingEndObjectGenerator.bind(undefined, stringDecoder),18 }19 : {20 transform: encodingEndStringGenerator.bind(undefined, stringDecoder),21 final: encodingEndStringFinal.bind(undefined, stringDecoder),22 };23 return [24 ...newStdioStreams,25 {26 ...newStdioStreams[0],27 type: 'generator',28 value: {...generator, binary: true, objectMode},29 encoding: 'buffer',30 },31 ];32};3334const shouldEncodeOutput = (stdioStreams, encoding, isSync) => stdioStreams[0].direction === 'output'35 && !IGNORED_ENCODINGS.has(encoding)36 && !isSync37 && willPipeStreams(stdioStreams);3839// eslint-disable-next-line unicorn/text-encoding-identifier-case40const IGNORED_ENCODINGS = new Set(['utf8', 'utf-8', 'buffer']);4142const encodingEndStringGenerator = function * (stringDecoder, chunk) {43 yield stringDecoder.write(chunk);44};4546const encodingEndStringFinal = function * (stringDecoder) {47 const lastChunk = stringDecoder.end();48 if (lastChunk !== '') {49 yield lastChunk;50 }51};5253const encodingEndObjectGenerator = function * (stringDecoder, chunk) {54 yield isUint8Array(chunk) ? stringDecoder.end(chunk) : chunk;55};