1# trough
2
3[![Build][build-badge]][build]
4[![Coverage][coverage-badge]][coverage]
5[![Downloads][downloads-badge]][downloads]
6[![Size][size-badge]][size]
7
8> **trough** /trôf/ — a channel used to convey a liquid.
9
10`trough` is like [`ware`][ware] with less sugar, and middleware functions can
11change the input of the next.
12
13## Install
14
15[npm][]:
16
17```sh
18npm install trough
19```
20
21## Use
22
23```js
24var fs = require('fs')
25var path = require('path')
26var trough = require('trough')
27
28var pipeline = trough()
29  .use(function(fileName) {
30    console.log('Checking… ' + fileName)
31  })
32  .use(function(fileName) {
33    return path.join(process.cwd(), fileName)
34  })
35  .use(function(filePath, next) {
36    fs.stat(filePath, function(err, stats) {
37      next(err, {filePath, stats})
38    })
39  })
40  .use(function(ctx, next) {
41    if (ctx.stats.isFile()) {
42      fs.readFile(ctx.filePath, next)
43    } else {
44      next(new Error('Expected file'))
45    }
46  })
47
48pipeline.run('readme.md', console.log)
49pipeline.run('node_modules', console.log)
50```
51
52Yields:
53
54```txt
55Checking… readme.md
56Checking… node_modules
57Error: Expected file
58    at ~/example.js:21:12
59    at wrapped (~/node_modules/trough/index.js:93:19)
60    at next (~/node_modules/trough/index.js:56:24)
61    at done (~/node_modules/trough/index.js:124:12)
62    at ~/node_modules/example.js:14:7
63    at FSReqWrap.oncomplete (fs.js:153:5)
64null <Buffer 23 20 74 72 6f 75 67 68 20 5b 21 5b 42 75 69 6c 64 20 53 74 61 74 75 73 5d 5b 74 72 61 76 69 73 2d 62 61 64 67 65 5d 5d 5b 74 72 61 76 69 73 5d 20 5b ... >
65```
66
67## API
68
69### `trough()`
70
71Create a new [`Trough`][trough].
72
73#### `trough.wrap(middleware, callback[, …input])`
74
75Call `middleware` with all input.
76If `middleware` accepts more arguments than given in input, and extra `done`
77function is passed in after the input when calling it.
78It must be called.
79
80The first value in `input` is called the main input value.
81All other input values are called the rest input values.
82The values given to `callback` are the input values, merged with every non-nully
83output value.
84
85*   If `middleware` throws an error, returns a promise that is rejected, or
86    calls the given `done` function with an error, `callback` is invoked with
87    that error
88*   If `middleware` returns a value or returns a promise that is resolved, that
89    value is the main output value
90*   If `middleware` calls `done`, all non-nully values except for the first one
91    (the error) overwrite the output values
92
93### `Trough`
94
95A pipeline.
96
97#### `Trough#run([input…, ]done)`
98
99Run the pipeline (all [`use()`][use]d middleware).
100Invokes [`done`][done] on completion with either an error or the output of the
101last middleware.
102
103> Note!
104> as the length of input defines whether [async][] functions get a `next`
105> function, it’s recommended to keep `input` at one value normally.
106
107##### `function done(err?, [output…])`
108
109The final handler passed to [`run()`][run], invoked with an error if a
110[middleware function][fn] rejected, passed, or threw one, or the output of the
111last middleware function.
112
113#### `Trough#use(fn)`
114
115Add `fn`, a [middleware function][fn], to the pipeline.
116
117##### `function fn([input…, ][next])`
118
119A middleware function invoked with the output of its predecessor.
120
121###### Synchronous
122
123If `fn` returns or throws an error, the pipeline fails and `done` is invoked
124with that error.
125
126If `fn` returns a value (neither `null` nor `undefined`), the first `input` of
127the next function is set to that value (all other `input` is passed through).
128
129The following example shows how returning an error stops the pipeline:
130
131```js
132var trough = require('trough')
133
134trough()
135  .use(function(val) {
136    return new Error('Got: ' + val)
137  })
138  .run('some value', console.log)
139```
140
141Yields:
142
143```txt
144Error: Got: some value
145    at ~/example.js:5:12
146147```
148
149The following example shows how throwing an error stops the pipeline:
150
151```js
152var trough = require('trough')
153
154trough()
155  .use(function(val) {
156    throw new Error('Got: ' + val)
157  })
158  .run('more value', console.log)
159```
160
161Yields:
162
163```txt
164Error: Got: more value
165    at ~/example.js:5:11
166167```
168
169The following example shows how the first output can be modified:
170
171```js
172var trough = require('trough')
173
174trough()
175  .use(function(val) {
176    return 'even ' + val
177  })
178  .run('more value', 'untouched', console.log)
179```
180
181Yields:
182
183```txt
184null 'even more value' 'untouched'
185```
186
187###### Promise
188
189If `fn` returns a promise, and that promise rejects, the pipeline fails and
190`done` is invoked with the rejected value.
191
192If `fn` returns a promise, and that promise resolves with a value (neither
193`null` nor `undefined`), the first `input` of the next function is set to that
194value (all other `input` is passed through).
195
196The following example shows how rejecting a promise stops the pipeline:
197
198```js
199var trough = require('trough')
200
201trough()
202  .use(function(val) {
203    return new Promise(function(resolve, reject) {
204      reject('Got: ' + val)
205    })
206  })
207  .run('val', console.log)
208```
209
210Yields:
211
212```txt
213Got: val
214```
215
216The following example shows how the input isn’t touched by resolving to `null`.
217
218```js
219var trough = require('trough')
220
221trough()
222  .use(function() {
223    return new Promise(function(resolve) {
224      setTimeout(function() {
225        resolve(null)
226      }, 100)
227    })
228  })
229  .run('Input', console.log)
230```
231
232Yields:
233
234```txt
235null 'Input'
236```
237
238###### Asynchronous
239
240If `fn` accepts one more argument than the given `input`, a `next` function is
241given (after the input).  `next` must be called, but doesn’t have to be called
242async.
243
244If `next` is given a value (neither `null` nor `undefined`) as its first
245argument, the pipeline fails and `done` is invoked with that value.
246
247If `next` is given no value (either `null` or `undefined`) as the first
248argument, all following non-nully values change the input of the following
249function, and all nully values default to the `input`.
250
251The following example shows how passing a first argument stops the pipeline:
252
253```js
254var trough = require('trough')
255
256trough()
257  .use(function(val, next) {
258    next(new Error('Got: ' + val))
259  })
260  .run('val', console.log)
261```
262
263Yields:
264
265```txt
266Error: Got: val
267    at ~/example.js:5:10
268```
269
270The following example shows how more values than the input are passed.
271
272```js
273var trough = require('trough')
274
275trough()
276  .use(function(val, next) {
277    setTimeout(function() {
278      next(null, null, 'values')
279    }, 100)
280  })
281  .run('some', console.log)
282```
283
284Yields:
285
286```txt
287null 'some' 'values'
288```
289
290## License
291
292[MIT][license] © [Titus Wormer][author]
293
294<!-- Definitions -->
295
296[build-badge]: https://img.shields.io/travis/wooorm/trough.svg
297
298[build]: https://travis-ci.org/wooorm/trough
299
300[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/trough.svg
301
302[coverage]: https://codecov.io/github/wooorm/trough
303
304[downloads-badge]: https://img.shields.io/npm/dm/trough.svg
305
306[downloads]: https://www.npmjs.com/package/trough
307
308[size-badge]: https://img.shields.io/bundlephobia/minzip/trough.svg
309
310[size]: https://bundlephobia.com/result?p=trough
311
312[npm]: https://docs.npmjs.com/cli/install
313
314[license]: license
315
316[author]: https://wooorm.com
317
318[ware]: https://github.com/segmentio/ware
319
320[trough]: #trough-1
321
322[use]: #troughusefn
323
324[run]: #troughruninput-done
325
326[fn]: #function-fninput-next
327
328[done]: #function-doneerr-output
329
330[async]: #asynchronous
331