Skip to content

Commit

Permalink
feat(size): add optional callback
Browse files Browse the repository at this point in the history
  • Loading branch information
olalonde committed Sep 19, 2016
1 parent ff288a3 commit 0d74896
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 4 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,7 @@ Transform stream that operates in object mode and returns a single `{
size: 1000 }` object where the size is an integer representing the total
size in bytes of the stream.

`new SizeStream()`
`new SizeStream()`

If passed a callback `new SizeStream(cb)` it will just act as a
PassThrough stream and call the callback when it's done.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "common-streams",
"version": "1.0.0",
"version": "1.0.1",
"description": "",
"main": "./lib/index.js",
"directories": {
Expand Down Expand Up @@ -56,4 +56,4 @@
"path": "cz-conventional-changelog"
}
}
}
}
15 changes: 14 additions & 1 deletion src/SizeStream.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,33 @@
import { Transform } from 'stream'

export default class SizeStream extends Transform {
constructor() {
constructor(cb) {
super({ objectMode: true })
this.streamSize = 0
this.cb = cb
}

_transform(chunk, encoding, cb) {
if (this.cb) return this._transformCb(chunk, encoding, cb)
// Update hash sum objects
this.streamSize = this.streamSize + chunk.length
cb()
}

_flush(cb) {
if (this.cb) return this._flushCb(cb)
const size = this.streamSize
this.push({ size })
cb(null)
}

_transformCb(chunk, encoding, cb) {
this.streamSize = this.streamSize + chunk.length
cb(null, chunk)
}
_flushCb(cb) {
const size = this.streamSize
this.cb(size)
cb(null)
}
}
17 changes: 17 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,20 @@ test('kitchen sink', (t) => {
}))
rs.pipe(ws)
})

test('size stream through', (t) => {
const rs = getReadStream()
const ws = getWriteStream()

t.plan(2)

const sizeStream = new SizeStream((size) => {
t.equal(size, 2447774)
})

ws.on('finish', () => {
t.ok(true)
})

rs.pipe(sizeStream).pipe(ws)
})

0 comments on commit 0d74896

Please sign in to comment.