fetch-remote-text-by-line.ts 1012 B

1234567891011121314151617181920212223242526
  1. import type { BunFile } from 'bun';
  2. import { fetchWithRetry, defaultRequestInit } from './fetch-retry';
  3. import { TextLineStream } from './text-line-transform-stream';
  4. import { PolyfillTextDecoderStream } from './text-decoder-stream';
  5. export function readFileByLine(file: string | BunFile) {
  6. if (typeof file === 'string') {
  7. file = Bun.file(file);
  8. }
  9. return file.stream().pipeThrough(new PolyfillTextDecoderStream()).pipeThrough(new TextLineStream());
  10. }
  11. export function createReadlineInterfaceFromResponse(resp: Response) {
  12. if (!resp.body) {
  13. throw new Error('Failed to fetch remote text');
  14. }
  15. if (resp.bodyUsed) {
  16. throw new Error('Body has already been consumed.');
  17. }
  18. return (resp.body as ReadableStream<Uint8Array>).pipeThrough(new PolyfillTextDecoderStream()).pipeThrough(new TextLineStream());
  19. }
  20. export function fetchRemoteTextAndCreateReadlineInterface(url: string | URL) {
  21. return fetchWithRetry(url, defaultRequestInit).then(res => createReadlineInterfaceFromResponse(res));
  22. }