encoding-final.js
This file
Path
lib/stdio/encoding-final.js
56 lines · 1.9 KiB · JavaScript
Last changed by
Improve default value of transforms `objectMode` (#867)ehmickybefore adoption8f51c6b
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import {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 lastObjectStdioStream = newStdioStreams.findLast(({type, value}) => type === 'generator' && value.objectMode !== undefined); const objectMode = lastObjectStdioStream !== undefined && lastObjectStdioStream.value.objectMode; const stringDecoder = new StringDecoder(encoding); const generator = objectMode ? { transform: encodingObjectGenerator.bind(undefined, stringDecoder), } : { transform: encodingStringGenerator.bind(undefined, stringDecoder), final: encodingStringFinal.bind(undefined, stringDecoder), }; return [ ...newStdioStreams, { ...newStdioStreams[0], type: 'generator', value: {...generator, binary: true}, 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 encodingStringGenerator = function * (stringDecoder, chunk) { yield stringDecoder.write(chunk);};
const encodingStringFinal = function * (stringDecoder) { const lastChunk = stringDecoder.end(); if (lastChunk !== '') { yield lastChunk; }};
const encodingObjectGenerator = function * (stringDecoder, chunk) { yield isUint8Array(chunk) ? stringDecoder.end(chunk) : chunk;};