forked from nodeca/probe-image-size
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream.js
60 lines (41 loc) · 1.27 KB
/
stream.js
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
'use strict';
var ProbeError = require('./lib/common').ProbeError;
var parsers = require('./lib/parsers_stream');
var PassThrough = require('stream').PassThrough;
var P;
module.exports = function probeStream(stream) {
// lazy Promise init
P = P || require('any-promise');
var proxy = new PassThrough();
var cnt = 0; // count of working parsers
var result = new P(function (resolve, reject) {
stream.on('error', reject);
proxy.on('error', reject);
function nope() {}
function parserEnd() {
proxy.unpipe(this);
this.removeAllListeners();
cnt--;
// if all parsers finished without success -> fail.
if (!cnt) reject(new ProbeError('unrecognized file format', 'ECONTENT'));
}
Object.keys(parsers).forEach(function (type) {
var pStream = parsers[type]();
cnt++;
pStream.once('data', resolve);
pStream.once('end', parserEnd);
// silently ignore errors because user does not need to know
// that something wrong is happening here
pStream.on('error', nope);
proxy.pipe(pStream);
});
});
function cleanup() {
stream.unpipe(proxy);
proxy.end();
}
result.then(cleanup).catch(cleanup);
stream.pipe(proxy);
return result;
};
module.exports.parsers = parsers;