fetch-remote-text-by-line.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // @ts-check
  2. const fs = require('fs');
  3. const { fetchWithRetry } = require('./fetch-retry');
  4. const readline = require('readline');
  5. const { Readable } = require('stream');
  6. /**
  7. * @param {string} path
  8. */
  9. module.exports.readFileByLine = (path) => {
  10. return readline.createInterface({
  11. input: fs.createReadStream(path, { encoding: 'utf-8' }),
  12. crlfDelay: Infinity
  13. });
  14. };
  15. /**
  16. * @param {import('undici').Response} resp
  17. */
  18. const createReadlineInterfaceFromResponse = (resp) => {
  19. if (!resp.body) {
  20. throw new Error('Failed to fetch remote text');
  21. }
  22. if (resp.bodyUsed) {
  23. throw new Error('Body has already been consumed.');
  24. }
  25. return readline.createInterface({
  26. input: Readable.fromWeb(resp.body),
  27. crlfDelay: Infinity
  28. });
  29. };
  30. module.exports.createReadlineInterfaceFromResponse = createReadlineInterfaceFromResponse;
  31. /**
  32. * @param {import('undici').RequestInfo} url
  33. * @param {import('undici').RequestInit | undefined} [opt]
  34. */
  35. module.exports.fetchRemoteTextAndCreateReadlineInterface = async (url, opt) => {
  36. const resp = await fetchWithRetry(url, opt);
  37. return createReadlineInterfaceFromResponse(resp);
  38. };