fetch-text-by-line.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import fs from 'node:fs';
  2. import readline from 'node:readline';
  3. import { TextLineStream } from 'foxts/text-line-stream';
  4. import type { ReadableStream } from 'node:stream/web';
  5. import { TextDecoderStream } from 'node:stream/web';
  6. import { processLine, ProcessLineStream } from './process-line';
  7. import { $$fetch } from './fetch-retry';
  8. import type { UndiciResponseData } from './fetch-retry';
  9. import type { Response as UnidiciWebResponse } from 'undici';
  10. import { invariant } from 'foxts/guard';
  11. export function readFileByLine(file: string): AsyncIterable<string> {
  12. return readline.createInterface({
  13. input: fs.createReadStream(file/* , { encoding: 'utf-8' } */),
  14. crlfDelay: Infinity
  15. });
  16. }
  17. export const createReadlineInterfaceFromResponse: ((resp: UndiciResponseData | UnidiciWebResponse, processLine?: boolean) => ReadableStream<string>) = (resp, processLine = false) => {
  18. invariant(resp.body, 'Failed to fetch remote text');
  19. if ('bodyUsed' in resp && resp.bodyUsed) {
  20. throw new Error('Body has already been consumed.');
  21. }
  22. let webStream: ReadableStream<Uint8Array>;
  23. if ('pipeThrough' in resp.body) {
  24. webStream = resp.body;
  25. } else {
  26. throw new TypeError('Invalid response body!');
  27. }
  28. const resultStream = webStream
  29. // @ts-expect-error -- mismatched Node.js and web types
  30. .pipeThrough(new TextDecoderStream())
  31. .pipeThrough(new TextLineStream({ skipEmptyLines: processLine }));
  32. if (processLine) {
  33. return resultStream.pipeThrough(new ProcessLineStream());
  34. }
  35. return resultStream;
  36. };
  37. export function fetchRemoteTextByLine(url: string, processLine = false): Promise<AsyncIterable<string>> {
  38. return $$fetch(url).then(resp => createReadlineInterfaceFromResponse(resp, processLine));
  39. }
  40. export async function readFileIntoProcessedArray(file: string /* | FileHandle */) {
  41. const results = [];
  42. let processed: string | null = '';
  43. for await (const line of readFileByLine(file)) {
  44. processed = processLine(line);
  45. if (processed) {
  46. results.push(processed);
  47. }
  48. }
  49. return results;
  50. }