fetch-text-by-line.ts 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import fs from 'node:fs';
  2. import { Readable } from 'node:stream';
  3. import fsp from 'node:fs/promises';
  4. import type { FileHandle } from 'node:fs/promises';
  5. import readline from 'node:readline';
  6. import { TextLineStream } from './text-line-transform-stream';
  7. import type { ReadableStream } from 'node:stream/web';
  8. import { TextDecoderStream } from 'node:stream/web';
  9. import { processLine, ProcessLineStream } from './process-line';
  10. import { $$fetch } from './fetch-retry';
  11. import type { UndiciResponseData } from './fetch-retry';
  12. import type { Response as UnidiciWebResponse } from 'undici';
  13. function getReadableStream(file: string | FileHandle): ReadableStream {
  14. if (typeof file === 'string') {
  15. // return fs.openAsBlob(file).then(blob => blob.stream())
  16. return Readable.toWeb(fs.createReadStream(file/* , { encoding: 'utf-8' } */));
  17. }
  18. return file.readableWebStream();
  19. }
  20. // TODO: use FileHandle.readLine()
  21. export const readFileByLineLegacy: ((file: string /* | FileHandle */) => AsyncIterable<string>) = (file: string | FileHandle) => getReadableStream(file)
  22. .pipeThrough(new TextDecoderStream())
  23. .pipeThrough(new TextLineStream());
  24. export function readFileByLine(file: string): AsyncIterable<string> {
  25. return readline.createInterface({
  26. input: fs.createReadStream(file/* , { encoding: 'utf-8' } */),
  27. crlfDelay: Infinity
  28. });
  29. }
  30. const fdReadLines = (fd: FileHandle) => fd.readLines();
  31. export async function readFileByLineNew(file: string): Promise<AsyncIterable<string>> {
  32. return fsp.open(file, 'r').then(fdReadLines);
  33. }
  34. function ensureResponseBody<T extends UndiciResponseData | UnidiciWebResponse>(resp: T): NonNullable<T['body']> {
  35. if (resp.body == null) {
  36. throw new Error('Failed to fetch remote text');
  37. }
  38. if ('bodyUsed' in resp && resp.bodyUsed) {
  39. throw new Error('Body has already been consumed.');
  40. }
  41. return resp.body;
  42. }
  43. export const createReadlineInterfaceFromResponse: ((resp: UndiciResponseData | UnidiciWebResponse, processLine?: boolean) => ReadableStream<string>) = (resp, processLine = false) => {
  44. const stream = ensureResponseBody(resp);
  45. const webStream: ReadableStream<Uint8Array> = 'getReader' in stream
  46. ? stream
  47. : (
  48. 'text' in stream
  49. ? stream.body as any
  50. : Readable.toWeb(new Readable().wrap(stream))
  51. );
  52. const resultStream = webStream
  53. .pipeThrough(new TextDecoderStream())
  54. .pipeThrough(new TextLineStream());
  55. if (processLine) {
  56. return resultStream.pipeThrough(new ProcessLineStream());
  57. }
  58. return resultStream;
  59. };
  60. export function fetchRemoteTextByLine(url: string, processLine = false): Promise<AsyncIterable<string>> {
  61. return $$fetch(url).then(resp => createReadlineInterfaceFromResponse(resp, processLine));
  62. }
  63. export async function readFileIntoProcessedArray(file: string /* | FileHandle */) {
  64. const results = [];
  65. for await (const line of readFileByLine(file)) {
  66. if (processLine(line)) {
  67. results.push(line);
  68. }
  69. }
  70. return results;
  71. }