Skip to content

Commit

Permalink
Merge pull request #1 from perrin4869/master
Browse files Browse the repository at this point in the history
Support stream encoding
  • Loading branch information
jasonpincin committed Jul 8, 2016
2 parents 4707c4f + 3d1098d commit 39a20b3
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ stream.end()
var toString = require('stream-to-string')
```

### toString(stream [, cb])
### toString(stream[, enc][, cb])

Collects stream data into a string. Executes optional callback with `err, string`. Returns a promise.
Collects stream data into a string. Accepts an optional encoding argument used when converting the stream. Executes optional callback with `err, string`. Returns a promise.

## testing

Expand Down
9 changes: 7 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
var Promise = require('promise-polyfill')

module.exports = function (stream, cb) {
module.exports = function (stream, enc, cb) {
if (typeof enc === 'function') {
cb = enc;
enc = null;
}
cb = cb || function () {}

var str = ''

return new Promise (function (resolve, reject) {
stream.on('data', function (data) {
str += data.toString()
str += (typeof enc === 'string') ? data.toString(enc) : data.toString()
})
stream.on('end', function () {
resolve(str)
Expand Down
14 changes: 14 additions & 0 deletions test/enc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
var test = require('tape'),
through2 = require('through2'),
toString = require('..')

test('enc', function (t) {
t.plan(1)

var stream = through2()
toString(stream, 'hex', function (err, str) {
t.equal(str, '68656c6c6f20776f726c64', 'should match expected value')
})

stream.end('hello world')
})

0 comments on commit 39a20b3

Please sign in to comment.