strong-tie/inbound-calls
0
1# duplexify2 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 input6and it allows you to set the readable and writable part asynchronously using `setReadable(stream)` and `setWritable(stream)`7 8```9npm install duplexify10```11 12[](http://travis-ci.org/mafintosh/duplexify)13 14## Usage15 16Use `duplexify(writable, readable, streamOptions)` (or `duplexify.obj(writable, readable)` to create an object stream)17 18``` js19var duplexify = require('duplexify')20 21// turn writableStream and readableStream into a single duplex stream22var dup = duplexify(writableStream, readableStream)23 24dup.write('hello world') // will write to writableStream25dup.on('data', function(data) {26 // will read from readableStream27})28```29 30You can also set the readable and writable parts asynchronously31 32``` js33var dup = duplexify()34 35dup.write('hello world') // write will buffer until the writable36 // part has been set37 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 an50error object as argument, in which case the error is emitted as part of the `error` event.51 52``` js53dup.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 example65 66Turn a node core http request into a duplex stream is as easy as67 68``` js69var 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 dup79}80 81var req = request({82 method: 'GET',83 host: 'www.google.com',84 port: 8085})86 87req.end()88req.pipe(process.stdout)89```90 91## License92 93MIT94 95## Related96 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.98 