Skip to content

mvisat/random-readable

Repository files navigation

random-readable

Create a readable stream of cryptographically secure random bytes using crypto.randomBytes.

Install

$ npm install --save random-readable

or

$ yarn add random-readable

Quick Usage

Output 16 random bytes to stdout.

const random = require('random-readable');

random.createRandomStream(16).pipe(process.stdout);

ES6/TypeScript Import

import createRandomStream from 'random-readable';

createRandomStream(16).pipe(process.stdout);

Advanced Usage

Infinite Stream

const random = require('random-readable');

// outputs infinite data to stdout.
const stream = random.createRandomStream();
stream.pipe(process.stdout);

// stop after 250ms to prevent infinite loop.
setTimeout(() => { stream.destroy(); }, 250);

Event Listeners

const random = require('random-readable');

random.createRandomStream(1000)
    .on('error', err => {
        // emitted error, if occured.
        // it is a best practice to listen on error event
        // and handle the error.
    })
    .on('data', data => {
       // chunk of random bytes generated.
       // you can use the data here,
       // such as updating hash value.
    })
    .on('end', () => {
        // no more data will be emitted.
        // you can finalize your action here,
        // such as finalizing hash value.
    })
    .pipe(process.stdout); // outputs 1000 random bytes to stdout

API

createRandomStream([size])

  • size?: number. Default: Infinity.
  • Returns: stream.Readable of random bytes.

size is how many bytes that will be generated by stream. If size is undefined, or has invalid value such as negative value or NaN, stream generates infinite random bytes.

License

MIT