try-stream-push

Push the return value of the function to the stream, or make it emit the thrown error


Keywords
try, catch, push, function, return, emit, error, stream, read
License
MIT
Install
bower install try-stream-push

Documentation

try-stream-push

NPM version Bower version Build Status Coverage Status devDependency Status

Push the return value of the function to the stream, or make the stream emit the thrown error

const {Transform} = require('stream');
const tryStreamPush = require('try-stream-push');

function createJSONParseStream() {
  return new Transform(
    objectMode: true,
    transform: function(data, enc, cb) {
      tryStreamPush(this, () => JSON.parse(String(data.contents)));
      cb();
    }
  });
};

It is useful to implement _transform method of a transform stream.

Installation

npm

npm install try-stream-push
bower install try-stream-push

API

const tryStreamPush = require('try-stream-push');

tryStreamPush(stream, fn [, errorHandler])

stream: Object (stream)
fn: Function
errorHandler: Function
Return: Boolean (the same as the return value of readable.push() when the function doesn't throw, otherwise the same as emitter.emit()'s)

It calls the function passed to the second argument.

If the function doesn't throw, it pushes the return value of the function to the stream passed to the first argument.

If the function throws an error, it makes the stream emit the error.

const {PassThrough} = require('stream');
const tryStreamPush = require('try-stream-push');

const all = {
  data: [],
  error: []
};

const stream = new PassThrough({objectMode: true})
  .on('data', data => all.data.push(data))
  .on('error', err => all.error.push(err));

tryStreamPush(stream, () => 'foo');
tryStreamPush(stream, () => {bar: 'baz'});
tryStreamPush(stream, () => throw new Error('error!'));

stream.on('end', () => {
  all.data; //=> ['foo', {bar: 'baz'}]
  all.error; //=> [[Error: error!]]
});

stram.end();

errorHandler(error)

error: Error

Takes the thrown error object and modifies it before emitting.

const gutil = require('gulp-util');
const {Transform} = require('stream');
const tryStreamPush = require('try-stream-push');

let stream = new Transform({
  objectMode: true,
  transform(data, enc, cb) {
    tryStreamPush(this, function() {
      // something
    }, function errorHandler(err) {
      // convert the default error into a gulp plugin error
      return gutil.PluginError('plugin-name', err);
    });

    cb();
  }
});

License

Copyright (c) 2014 - 2016 Shinnosuke Watanabe

Licensed under the MIT License.