https://github.com/raine/hook-stream
Hook into writes of a stream
https://github.com/raine/hook-stream
nodejs stderr stdout stream
Last synced: 3 months ago
JSON representation
Hook into writes of a stream
- Host: GitHub
- URL: https://github.com/raine/hook-stream
- Owner: raine
- Created: 2019-01-17T10:28:21.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2019-01-18T15:00:34.000Z (over 6 years ago)
- Last Synced: 2025-06-29T22:37:29.042Z (3 months ago)
- Topics: nodejs, stderr, stdout, stream
- Language: JavaScript
- Homepage:
- Size: 13.7 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# hook-stream
Allows listening to a given stream's writes through a new, readable stream.
Useful for listening to a 3rd party library's writes to `stdout` or `stderr`.
## install
```sh
npm install --save hook-stream
```## API
#### `hookStream(stream: Stream, options?: Object): [unhook: Function, readable: Stream]`
Takes a `stream` to hook into and optional `options` object.
Returns a tuple of `unhook` function and a newly created readable stream that
emits writes to `stream`.## example
Direct writes to `stderr` to `stdout`.
```js
const hookStream = require('hook-stream')
const map = require('through2-map')
const treis = require('treis')const [ unhook, stream ] = hookStream(process.stderr)
stream
.pipe(map((x) => `STDOUT ${x}`))
.pipe(process.stdout)console.error('foo')
process.stderr.write('bar')
// treis prints function input and output to stderr
treis(x => x)(1)unhook()
```### output
```sh
% node examples/1.js
STDOUT foo
foo
STDOUT bar
bar
STDOUT λ1 x: 1
λ1 x: 1
STDOUT λ1 => 1
λ1 => 1
```## caveat
This method does not work if a third party lib saves a reference to "original"
`stream.write` (e.g. `process.stderr.write`) before `hookStream` is called.```js
// somewhere else, maybe in some lib's code
const log = process.stderr.write.bind(process.stderr)// .....
// won't work because hookStream replaces process.stderr.write with its own
// function, but log already has reference to the original
const [ unhook, stream ] = hookStream(process.stderr)
```