Projekt

Obecné

Profil

Stáhnout (1.22 KB) Statistiky
| Větev: | Revize:
1
'use strict';
2
const pump = require('pump');
3
const bufferStream = require('./buffer-stream');
4

    
5
class MaxBufferError extends Error {
6
	constructor() {
7
		super('maxBuffer exceeded');
8
		this.name = 'MaxBufferError';
9
	}
10
}
11

    
12
function getStream(inputStream, options) {
13
	if (!inputStream) {
14
		return Promise.reject(new Error('Expected a stream'));
15
	}
16

    
17
	options = Object.assign({maxBuffer: Infinity}, options);
18

    
19
	const {maxBuffer} = options;
20

    
21
	let stream;
22
	return new Promise((resolve, reject) => {
23
		const rejectPromise = error => {
24
			if (error) { // A null check
25
				error.bufferedData = stream.getBufferedValue();
26
			}
27
			reject(error);
28
		};
29

    
30
		stream = pump(inputStream, bufferStream(options), error => {
31
			if (error) {
32
				rejectPromise(error);
33
				return;
34
			}
35

    
36
			resolve();
37
		});
38

    
39
		stream.on('data', () => {
40
			if (stream.getBufferedLength() > maxBuffer) {
41
				rejectPromise(new MaxBufferError());
42
			}
43
		});
44
	}).then(() => stream.getBufferedValue());
45
}
46

    
47
module.exports = getStream;
48
module.exports.buffer = (stream, options) => getStream(stream, Object.assign({}, options, {encoding: 'buffer'}));
49
module.exports.array = (stream, options) => getStream(stream, Object.assign({}, options, {array: true}));
50
module.exports.MaxBufferError = MaxBufferError;
(2-2/5)