fetch-remote-text-by-line.js 907 B

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