helpers.mjs 902 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict';
  2. import {Readable, Writable} from 'stream';
  3. export const streamToArray = array =>
  4. new Writable({
  5. objectMode: true,
  6. write(chunk, _, callback) {
  7. array.push(chunk);
  8. callback(null);
  9. }
  10. });
  11. export const readString = (string, quant) => new Readable({
  12. read() {
  13. if (isNaN(quant) || quant < 1) {
  14. this.push(string);
  15. } else if (string instanceof Buffer) {
  16. for (let i = 0; i < string.length; i += quant) {
  17. this.push(string.slice(i, i + quant));
  18. }
  19. } else {
  20. for (let i = 0; i < string.length; i += quant) {
  21. this.push(string.substr(i, quant));
  22. }
  23. }
  24. this.push(null);
  25. }
  26. });
  27. export const delay = (fn, ms = 20) => async (...args) =>
  28. new Promise((resolve, reject) => {
  29. setTimeout(() => {
  30. try {
  31. resolve(fn(...args));
  32. } catch (error) {
  33. reject(error);
  34. }
  35. }, ms);
  36. });