fetch-text-by-line.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. const decoder = new TextDecoder('utf-8');
  21. async function *createTextLineAsyncGeneratorFromStreamSource(stream: ReadableStream<Uint8Array>): AsyncGenerator<string> {
  22. let buf = '';
  23. for await (const chunk of stream) {
  24. const chunkStr = decoder.decode(chunk).replaceAll('\r\n', '\n');
  25. for (let i = 0, len = chunkStr.length; i < len; i++) {
  26. const char = chunkStr[i];
  27. if (char === '\n') {
  28. yield buf;
  29. buf = '';
  30. } else {
  31. buf += char;
  32. }
  33. }
  34. }
  35. if (buf) {
  36. yield buf;
  37. }
  38. }
  39. export function readFileByLine(file: string | URL | BunFile): AsyncGenerator<string> {
  40. if (typeof file === 'string') {
  41. file = Bun.file(file);
  42. } else if (!('writer' in file)) {
  43. file = Bun.file(file);
  44. }
  45. return createTextLineAsyncGeneratorFromStreamSource(file.stream());
  46. }
  47. export function createReadlineInterfaceFromResponse(resp: Response): AsyncGenerator<string> {
  48. if (!resp.body) {
  49. throw new Error('Failed to fetch remote text');
  50. }
  51. if (resp.bodyUsed) {
  52. throw new Error('Body has already been consumed.');
  53. }
  54. return createTextLineAsyncGeneratorFromStreamSource(resp.body);
  55. }
  56. export function fetchRemoteTextByLine(url: string | URL) {
  57. return fetchWithRetry(url, defaultRequestInit).then(res => createReadlineInterfaceFromResponse(res));
  58. }