string.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import {getStreamContents} from './contents.js';
  2. import {
  3. identity,
  4. getContentsProperty,
  5. throwObjectStream,
  6. getLengthProperty,
  7. } from './utils.js';
  8. export async function getStreamAsString(stream, options) {
  9. return getStreamContents(stream, stringMethods, options);
  10. }
  11. const initString = () => ({contents: '', textDecoder: new TextDecoder()});
  12. const useTextDecoder = (chunk, {textDecoder}) => textDecoder.decode(chunk, {stream: true});
  13. const addStringChunk = (convertedChunk, {contents}) => contents + convertedChunk;
  14. const truncateStringChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize);
  15. const getFinalStringChunk = ({textDecoder}) => {
  16. const finalChunk = textDecoder.decode();
  17. return finalChunk === '' ? undefined : finalChunk;
  18. };
  19. const stringMethods = {
  20. init: initString,
  21. convertChunk: {
  22. string: identity,
  23. buffer: useTextDecoder,
  24. arrayBuffer: useTextDecoder,
  25. dataView: useTextDecoder,
  26. typedArray: useTextDecoder,
  27. others: throwObjectStream,
  28. },
  29. getSize: getLengthProperty,
  30. truncateChunk: truncateStringChunk,
  31. addChunk: addStringChunk,
  32. getFinalChunk: getFinalStringChunk,
  33. finalize: getContentsProperty,
  34. };