index.js
1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'use strict';
var Writable = require('readable-stream').Writable;
var inherits = require('util').inherits;
var Promise = require('pinkie-promise');
function BufferStream() {
Writable.call(this, { objectMode: true });
this.buffer = [];
this.length = 0;
}
inherits(BufferStream, Writable);
BufferStream.prototype._write = function(chunk, enc, next) {
if (!Buffer.isBuffer(chunk)) {
chunk = new Buffer(chunk);
}
this.buffer.push(chunk);
this.length += chunk.length;
next();
};
module.exports = function read(stream, options, cb) {
if (!stream) {
throw new Error('stream argument is required');
}
if (typeof options === 'function') {
cb = options;
options = {};
}
if (typeof options === 'string' || options === undefined || options === null) {
options = { encoding: options };
}
if (options.encoding === undefined) { options.encoding = 'utf8'; }
var promise;
if (!cb) {
var resolve, reject;
promise = new Promise(function(_res, _rej) {
resolve = _res;
reject = _rej;
});
cb = function (err, data) {
if (err) { return reject(err); }
resolve(data);
};
}
var sink = new BufferStream();
sink.on('finish', function () {
var data = Buffer.concat(this.buffer, this.length);
if (options.encoding) {
data = data.toString(options.encoding);
}
cb(null, data);
});
stream.once('error', cb);
stream.pipe(sink);
return promise;
}