peek-readable
A promise based asynchronous stream reader, which makes reading from a stream easy.
Allows to read and peek from a Readable Stream
Note that peek-readable was formally released as then-read-stream.
Usage
Installation
shell script npm install --save peek-readable
The peek-readable
contains one class:
StreamReader
, which reads from a stream.Readable.
Compatibility
NPM module is compliant with ECMAScript 2017 (ES8).
Examples
In the following example we read the first 16 bytes from a stream and store them in our buffer. Source code of examples can be found here.
const fs = require('fs');
const { StreamReader } = require('peek-readable');
async () => {
(
const fileReadStream = fs.createReadStream('JPEG_example_JPG_RIP_001.jpg');
const streamReader = new StreamReader(fileReadStream);
const buffer = Buffer.alloc(16);
const bytesRead = await streamReader.read(buffer, 0, 16);
// buffer contains 16 bytes, if the end-of-stream has not been reached
; })()
End-of-stream detection:
async () => {
(
const fileReadStream = fs.createReadStream('JPEG_example_JPG_RIP_001.jpg');
const streamReader = new StreamReader(fileReadStream);
const buffer = Buffer.alloc(16);
try {
await streamReader.read(buffer, 0, 16);
// buffer contains 16 bytes, if the end-of-stream has not been reached
catch(error) {
} if (error instanceof EndOfStreamError) {
console.log('End-of-stream reached');
}
}; })()
With peek you can read ahead:
const fs = require('fs');
const { StreamReader } = require('peek-readable');
const fileReadStream = fs.createReadStream('JPEG_example_JPG_RIP_001.jpg');
const streamReader = new StreamReader(fileReadStream);
const buffer = Buffer.alloc(20);
async () => {
(let bytesRead = await streamReader.peek(buffer, 0, 3);
if (bytesRead === 3 && buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[2] === 0xFF) {
console.log('This is a JPEG file');
else {
} throw Error('Expected a JPEG file');
}
= await streamReader.read(buffer, 0, 20); // Read JPEG header
bytesRead if (bytesRead === 20) {
console.log('Got the JPEG header');
else {
} throw Error('Failed to read JPEG header');
}; })()
If you have to skip a part of the data, you can use ignore:
async () => {
(//...
await streamReader.ignore(16);
; })()