UNPKG

2.7 kBMarkdownView Raw
1# duplexify
2
3Turn a writeable and readable stream into a single streams2 duplex stream.
4
5Similar to [duplexer2](https://github.com/deoxxa/duplexer2) except it supports both streams2 and streams1 as input
6and it allows you to set the readable and writable part asynchronously using `setReadable(stream)` and `setWritable(stream)`
7
8```
9npm install duplexify
10```
11
12[![build status](http://img.shields.io/travis/mafintosh/duplexify.svg?style=flat)](http://travis-ci.org/mafintosh/duplexify)
13
14## Usage
15
16Use `duplexify(writable, readable, streamOptions)` (or `duplexify.obj(writable, readable)` to create an object stream)
17
18``` js
19var duplexify = require('duplexify')
20
21// turn writableStream and readableStream into a single duplex stream
22var dup = duplexify(writableStream, readableStream)
23
24dup.write('hello world') // will write to writableStream
25dup.on('data', function(data) {
26 // will read from readableStream
27})
28```
29
30You can also set the readable and writable parts asynchronously
31
32``` js
33var dup = duplexify()
34
35dup.write('hello world') // write will buffer until the writable
36 // part has been set
37
38// wait a bit ...
39dup.setReadable(readableStream)
40
41// maybe wait some more?
42dup.setWritable(writableStream)
43```
44
45If you call `setReadable` or `setWritable` multiple times it will unregister the previous readable/writable stream.
46To disable the readable or writable part call `setReadable` or `setWritable` with `null`.
47
48If the readable or writable streams emits an error or close it will destroy both streams and bubble up the event.
49You can also explicitly destroy the streams by calling `dup.destroy()`. The `destroy` method optionally takes an
50error object as argument, in which case the error is emitted as part of the `error` event.
51
52``` js
53dup.on('error', function(err) {
54 console.log('readable or writable emitted an error - close will follow')
55})
56
57dup.on('close', function() {
58 console.log('the duplex stream is destroyed')
59})
60
61dup.destroy() // calls destroy on the readable and writable part (if present)
62```
63
64## HTTP request example
65
66Turn a node core http request into a duplex stream is as easy as
67
68``` js
69var duplexify = require('duplexify')
70var http = require('http')
71
72var request = function(opts) {
73 var req = http.request(opts)
74 var dup = duplexify(req)
75 req.on('response', function(res) {
76 dup.setReadable(res)
77 })
78 return dup
79}
80
81var req = request({
82 method: 'GET',
83 host: 'www.google.com',
84 port: 80
85})
86
87req.end()
88req.pipe(process.stdout)
89```
90
91## License
92
93MIT
94
95## Related
96
97`duplexify` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one.