Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. const { Readable } = require("stream");
  2.  
  3. class ReadableTest extends Readable {
  4. constructor() {
  5. super({ highWaterMark: 256 });
  6. this.source = Buffer.from(`abcdefghijklmnopqrstuvwxyz..
  7. The quick brown fox jumps over the lazy dog.
  8. The quick brown fox jumps over the lazy dog.
  9. The quick brown fox jumps over the lazy dog.
  10. The quick brown fox jumps over the lazy dog.
  11. The quick brown fox jumps over the lazy dog. 🚀`);
  12. this.pos = 0;
  13. }
  14.  
  15. _read(size) {
  16. console.log("_read", size);
  17. let start = this.pos;
  18. let end = Math.min(start + size, this.source.length);
  19. this.pos = end;
  20. if (start < end) {
  21. console.log("push", end - start);
  22. this.push(this.source.slice(start, end));
  23. } else {
  24. console.log("push end");
  25. this.push(null);
  26. }
  27. }
  28. }
  29.  
  30. function runTest(shouldSetEncoding) {
  31. return new Promise((resolve, reject) => {
  32. const readable = new ReadableTest();
  33. if (shouldSetEncoding) {
  34. readable.setEncoding("utf8");
  35. }
  36. let body = "";
  37. readable.on("data", chunk => {
  38. body += chunk;
  39. console.log("ondata body.length", body.length);
  40. });
  41. readable.on("error", reject);
  42. readable.on("end", () => resolve(body));
  43. });
  44. }
  45.  
  46. async function main() {
  47. console.log("readable.on('data', chunk.toString()) without setEncoding");
  48. console.log(await runTest(false));
  49. console.log("readable.on('data', chunk) with setEncoding");
  50. console.log(await runTest(true));
  51. }
  52.  
  53. main();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement