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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import {StringDecoder} from 'node:string_decoder';import {isUint8Array} from '../utils.js';import {willPipeStreams} from './forward.js';
// Apply the `encoding` option using an implicit generator.// This encodes the final output of `stdout`/`stderr`.export const handleStreamsEncoding = (stdioStreams, {encoding}, isSync) => { const newStdioStreams = stdioStreams.map(stdioStream => ({...stdioStream, encoding})); if (!shouldEncodeOutput(newStdioStreams, encoding, isSync)) { return newStdioStreams; }
const objectMode = newStdioStreams.findLast(({type}) => type === 'generator')?.value.objectMode === true; const stringDecoder = new StringDecoder(encoding); const generator = objectMode ? { transform: encodingEndObjectGenerator.bind(undefined, stringDecoder), } : { transform: encodingEndStringGenerator.bind(undefined, stringDecoder), final: encodingEndStringFinal.bind(undefined, stringDecoder), }; return [ ...newStdioStreams, { ...newStdioStreams[0], type: 'generator', value: {...generator, binary: true, objectMode}, encoding: 'buffer', }, ];};
const shouldEncodeOutput = (stdioStreams, encoding, isSync) => stdioStreams[0].direction === 'output' && !IGNORED_ENCODINGS.has(encoding) && !isSync && willPipeStreams(stdioStreams);
// eslint-disable-next-line unicorn/text-encoding-identifier-caseconst IGNORED_ENCODINGS = new Set(['utf8', 'utf-8', 'buffer']);
const encodingEndStringGenerator = function * (stringDecoder, chunk) { yield stringDecoder.write(chunk);};
const encodingEndStringFinal = function * (stringDecoder) { const lastChunk = stringDecoder.end(); if (lastChunk !== '') { yield lastChunk; }};
const encodingEndObjectGenerator = function * (stringDecoder, chunk) { yield isUint8Array(chunk) ? stringDecoder.end(chunk) : chunk;};