Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { Readable } = require("stream");
- class ReadableTest extends Readable {
- constructor() {
- super({ highWaterMark: 256 });
- this.source = Buffer.from(`abcdefghijklmnopqrstuvwxyz..
- The quick brown fox jumps over the lazy dog.
- The quick brown fox jumps over the lazy dog.
- The quick brown fox jumps over the lazy dog.
- The quick brown fox jumps over the lazy dog.
- The quick brown fox jumps over the lazy dog. 🚀`);
- this.pos = 0;
- }
- _read(size) {
- console.log("_read", size);
- let start = this.pos;
- let end = Math.min(start + size, this.source.length);
- this.pos = end;
- if (start < end) {
- console.log("push", end - start);
- this.push(this.source.slice(start, end));
- } else {
- console.log("push end");
- this.push(null);
- }
- }
- }
- function runTest(shouldSetEncoding) {
- return new Promise((resolve, reject) => {
- const readable = new ReadableTest();
- if (shouldSetEncoding) {
- readable.setEncoding("utf8");
- }
- let body = "";
- readable.on("data", chunk => {
- body += chunk;
- console.log("ondata body.length", body.length);
- });
- readable.on("error", reject);
- readable.on("end", () => resolve(body));
- });
- }
- async function main() {
- console.log("readable.on('data', chunk.toString()) without setEncoding");
- console.log(await runTest(false));
- console.log("readable.on('data', chunk) with setEncoding");
- console.log(await runTest(true));
- }
- main();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement