Created
February 21, 2019 05:27
-
-
Save krisselden/546b7e594743d40ac9857fb8bf348821 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment