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.
npm install try-stream-push
bower install try-stream-push
const tryStreamPush = require('try-stream-push');
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();
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();
}
});
Copyright (c) 2014 - 2016 Shinnosuke Watanabe
Licensed under the MIT License.