https://github.com/mvisat/random-readable
Generate a readable stream of random bytes
https://github.com/mvisat/random-readable
nodejs random-bytes readable-stream typescript
Last synced: 8 days ago
JSON representation
Generate a readable stream of random bytes
- Host: GitHub
- URL: https://github.com/mvisat/random-readable
- Owner: mvisat
- License: mit
- Created: 2018-06-20T07:30:01.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2018-08-17T10:42:11.000Z (over 7 years ago)
- Last Synced: 2025-08-30T11:47:20.226Z (8 months ago)
- Topics: nodejs, random-bytes, readable-stream, typescript
- Language: TypeScript
- Homepage:
- Size: 176 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# random-readable
Create a [readable stream](https://nodejs.org/api/stream.html#stream_readable_streams) of cryptographically secure random bytes using [crypto.randomBytes](https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback).
## Install
```
$ npm install --save random-readable
```
or
```
$ yarn add random-readable
```
## Quick Usage
Output 16 random bytes to `stdout`.
```js
const random = require('random-readable');
random.createRandomStream(16).pipe(process.stdout);
```
### ES6/TypeScript Import
```ts
import createRandomStream from 'random-readable';
createRandomStream(16).pipe(process.stdout);
```
## Advanced Usage
### Infinite Stream
```js
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
```js
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](LICENSE)