aboutsummaryrefslogtreecommitdiff
path: root/node_modules/multipipe/index.js
blob: 5e406db88c26d9dd5b1e8baea6696bbcd1ef7859 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

/**
 * Module dependencies.
 */

var duplexer = require('duplexer2');
var Stream = require('stream');

/**
 * Slice reference.
 */

var slice = [].slice;

/**
 * Duplexer options.
 */

var opts = {
  bubbleErrors: false
};

/**
 * Expose `pipe`.
 */

module.exports = pipe;

/**
 * Pipe.
 *
 * @param {Stream,...,[Function]}
 * @return {Stream}
 * @api public
 */

function pipe(){
  if (arguments.length == 1) return arguments[0];
  var streams = slice.call(arguments);
  var cb;
  if ('function' == typeof streams[streams.length - 1]) {
    cb = streams.splice(-1)[0];
  }
  var first = streams[0];
  var last = streams[streams.length - 1];
  var ret;
  
  if (first.writable && last.readable) ret = duplexer(opts, first, last);
  else if (first.writable) ret = first;
  else if (last.readable) ret = last;
  else ret = new Stream;
  
  streams.forEach(function(stream, i){
    var next = streams[i+1];
    if (next) stream.pipe(next);
    if (stream != ret) stream.on('error', ret.emit.bind(ret, 'error'));
  });

  if (cb) {
    var ended = false;
    ret.on('error', end);
    last.on('finish', end);
    function end(err){
      if (ended) return;
      ended = true;
      cb(err);
    }
  }

  return ret;
}