Skip to content

Instantly share code, notes, and snippets.

@artze
Created June 8, 2019 08:44
Show Gist options
  • Save artze/2ca084b462753ce7fd75705448f1c173 to your computer and use it in GitHub Desktop.
Save artze/2ca084b462753ce7fd75705448f1c173 to your computer and use it in GitHub Desktop.
Create a Readable Stream implementation that generates random strings
const stream = require('stream');
const Chance = require('chance');
const chance = new Chance();
class RandomStream extends stream.Readable {
constructor(options) {
super(options);
}
_read(size) {
const chunk = chance.string(); // [1]
console.log(`Pushing chunk of size: ${chunk.length}`);
this.push(chunk, 'utf8'); // [2]
if(chance.bool({ likelihood: 5 })) { // [3]
this.push(null);
}
}
}
// [1] Generates a random string using chance lib
// [2] Pushes the string into the internal reading buffer. Since we are
// pushing String, the encoding is specified
// [3] The bool method returns true at a 5% likelihood. In this case, null
// is pushed into internal buffer which triggers the 'end' event
// Usage of RandomStream
const randomStream = new RandomStream();
randomStream
.on('readable', () => {
let chunk;
while((chunk = randomStream.read()) !== null) {
console.log(`Chunk received: ${chunk.toString()}`);
}
})
.on('end', () => console.log('End of stream'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment