-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
55 lines (50 loc) · 1.21 KB
/
index.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
/**
* http-image-size: Detect image dimensions via http.
*
* Licensed under the MIT license.
* https://github.com/jo/http-image-size
* © 2014 Johannes J. Schmidt
*
*/
'use strict';
var url = require('url');
var http = require('http');
var https = require('https');
var sizeOf = require('image-size');
module.exports = function(imgUrl, done) {
var options = url.parse(imgUrl);
var client;
if (options.protocol === 'https:') {
client = https;
} else if (options.protocol === 'http:') {
client = http;
} else {
throw new Error('The string should have "http" or "https" scheme.');
}
var req = client.get(options, function(response) {
var buffer = new Buffer([]);
var dimensions;
var imageTypeDetectionError;
response
.on('data', function(chunk) {
buffer = Buffer.concat([buffer, chunk]);
try {
dimensions = sizeOf(buffer);
} catch (e) {
imageTypeDetectionError = e;
return;
}
req.abort();
})
.on('error', function(err) {
done(err);
})
.on('end', function() {
if (!dimensions) {
done(imageTypeDetectionError);
return;
}
done(null, dimensions, buffer.length);
});
});
};