securityos/node_modules/then-read-stream/README.md

3.3 KiB

Build Status NPM version npm downloads Dependencies Coverage Status Codacy Badge Known Vulnerabilities

then-read-stream

A promise based asynchronous stream reader, which makes reading from a stream easy.

Allows to read from a Readable Stream similar as you would read from a file.

Usage

The then-read-stream contains one class: StreamReader, which reads from a stream.Readable.

Compatibility

NPM module is compliant with ECMAScript 2015 (ES6).

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.

import * as fs from 'fs';
import * as path from 'path';
import { StreamReader } from 'then-read-stream';

const readable = fs.createReadStream('JPEG_example_JPG_RIP_001.jpg');
const streamReader = new StreamReader(readable);

const buffer = Buffer.alloc(16);

return streamReader.read(buffer, 0, 16)
  .then( bytesRead => {
    // buf, contains bytesRead, which will be 16 if the end-of-stream has not been reached
  });

With peek you can read ahead:

import * as fs from 'fs';
import * as path from 'path';
import { StreamReader } from 'then-read-stream';

const fileReadStream = fs.createReadStream('JPEG_example_JPG_RIP_001.jpg');
const streamReader = new StreamReader(fileReadStream);
const buffer = Buffer.alloc(20);

return streamReader.peek(buffer, 0, 3)
  .then(bytesRead => {
    if (bytesRead === 3 && buffer[0] === 0xFF && buffer[1] === 0xD8 && buffer[2] === 0xFF) {
      console.log('This is a JPEG file');
      return streamReader.read(buffer, 0, 20); // Read JPEG header
    } else {
      throw Error('Expected a JPEG file');
    }
  })
  .then(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:

return streamReader.ignore(16)
  .then( bytesIgnored => {
    if (bytesIgnored < 16){
      console.log(`Remaining stream length was ${bytesIgnored}, expected 16`);
    }
  });