1 | 'use strict';
|
2 |
|
3 | var fs = require('fs');
|
4 | var path = require('path');
|
5 |
|
6 | var typeHandlers = require('./types');
|
7 | var detector = require('./detector');
|
8 |
|
9 |
|
10 |
|
11 | var MaxBufferSize = 512*1024;
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | function lookup (buffer, filepath) {
|
21 |
|
22 | var type = detector(buffer, filepath);
|
23 |
|
24 |
|
25 | if (type in typeHandlers) {
|
26 | var size = typeHandlers[type].calculate(buffer, filepath);
|
27 | if (size !== false) {
|
28 | size.type = type;
|
29 | return size;
|
30 | }
|
31 | }
|
32 |
|
33 |
|
34 | throw new TypeError('unsupported file type: ' + type + ' (file: ' + filepath + ')');
|
35 | }
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 | function asyncFileToBuffer (filepath, callback) {
|
48 |
|
49 | fs.open(filepath, 'r', function (err, descriptor) {
|
50 | if (err) { return callback(err); }
|
51 | fs.fstat(descriptor, function (err, stats) {
|
52 | if (err) { return callback(err); }
|
53 | var size = stats.size;
|
54 | if (size <= 0) {
|
55 | return callback(new Error('File size is not greater than 0 —— ' + filepath));
|
56 | }
|
57 | var bufferSize = Math.min(size, MaxBufferSize);
|
58 | var buffer = Buffer.alloc(bufferSize);
|
59 |
|
60 | fs.read(descriptor, buffer, 0, bufferSize, 0, function (err) {
|
61 | if (err) { return callback(err); }
|
62 |
|
63 | fs.close(descriptor, function (err) {
|
64 | callback(err, buffer);
|
65 | });
|
66 | });
|
67 | });
|
68 | });
|
69 | }
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 | function syncFileToBuffer (filepath) {
|
78 |
|
79 | var descriptor = fs.openSync(filepath, 'r');
|
80 | var size = fs.fstatSync(descriptor).size;
|
81 | var bufferSize = Math.min(size, MaxBufferSize);
|
82 | var buffer = Buffer.alloc(bufferSize);
|
83 | fs.readSync(descriptor, buffer, 0, bufferSize, 0);
|
84 | fs.closeSync(descriptor);
|
85 | return buffer;
|
86 | }
|
87 |
|
88 |
|
89 |
|
90 |
|
91 |
|
92 | module.exports = function (input, callback) {
|
93 |
|
94 |
|
95 | if (Buffer.isBuffer(input)) {
|
96 | return lookup(input);
|
97 | }
|
98 |
|
99 |
|
100 | if (typeof input !== 'string') {
|
101 | throw new TypeError('invalid invocation');
|
102 | }
|
103 |
|
104 |
|
105 | var filepath = path.resolve(input);
|
106 |
|
107 | if (typeof callback === 'function') {
|
108 | asyncFileToBuffer(filepath, function (err, buffer) {
|
109 | if (err) { return callback(err); }
|
110 |
|
111 |
|
112 | var dimensions;
|
113 | try {
|
114 | dimensions = lookup(buffer, filepath);
|
115 | } catch (e) {
|
116 | err = e;
|
117 | }
|
118 | callback(err, dimensions);
|
119 | });
|
120 | } else {
|
121 | var buffer = syncFileToBuffer(filepath);
|
122 | return lookup(buffer, filepath);
|
123 | }
|
124 | };
|
125 |
|
126 | module.exports.types = Object.keys(typeHandlers);
|