All Projects → watson → stream-observer

watson / stream-observer

Licence: MIT License
Listen for data events on a readable stream without triggering flowing mode

Programming Languages

javascript
184084 projects - #8 most used programming language

stream-observer

Listen for data events on a readable stream without triggering flowing mode.

npm

Build status js-standard-style

Why?

Normally a readable stream will start to emit data events (i.e. enter "flowing mode") right after you attach the first data event listener.

But sometimes it's desirable to attach a data event listener without the side effect of enabling flowing mode.

E.g. if you want to subscribe to the content of a stream but are not in charge of when the stream starts flowing - say for instance if you hand the stream off to someone else that are not attaching their own data event listener right away.

This module gives you that ability.

Installation

npm install stream-observer --save

Usage

const fs = require('fs')
const streamObserver = require('stream-observer')

const stream = fs.createReadStream(__filename)

// Register observer to listen for data events once the stream starts
// flowing. Callback will be called with the data chunks.
streamObserver(stream, function (chunk) {
  console.log(`stream produced ${chunk.length} bytes of data`)
})

// Wait a little before starting to read data from the stream.
setTimeout(function () {
  stream.pipe(process.stdout)
}, 1000)

API

fn = streamObserver(stream, callback)

Arguments:

  • stream - the readable stream you wish to observe
  • callback - the callback will be attached to the data event of the stream without triggering flowing mode

Returns a function that you can call if you want to observer to stop observing.

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].