try-stream-push

1.1.0 • Public • Published

try-stream-push

NPM version Bower version Build Status Build status Coverage Status devDependency Status

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

var through = require('through2');
var tryStreamPush = require('try-stream-push');
 
function createJSONParseStream() {
  return through.obj(function(data, enc, cb) {
    tryStreamPush(this, function() {
      return 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

bower install try-stream-push

API

var 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.

var through = require('');
var tryStreamPush = require('try-stream-push');
 
var all = {
  data: [],
  error: []
};
 
var stream = through.obj()
  .on('data', function(data) {
    all.data.push(data);
  })
  .on('error', function(err) {
    all.error.push(err);
  });
 
tryStreamPush(stream, function() {
  return 'foo';
});
 
tryStreamPush(stream, function() {
  return {bar: 'baz'};
});
 
tryStreamPush(stream, function() {
  throw new Error('error!');
});
 
stream.on('end', function() {
  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.

var gutil = require('gulp-util');
var through = require('through2');
var tryStreamPush = require('try-stream-push');
 
var stream = through.obj(function(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 Shinnosuke Watanabe

Licensed under the MIT License.

Package Sidebar

Install

npm i try-stream-push

Weekly Downloads

22

Version

1.1.0

License

none

Last publish

Collaborators

  • shinnn