-
Notifications
You must be signed in to change notification settings - Fork 0
/
mimeTypeHelper.js
72 lines (64 loc) · 1.71 KB
/
mimeTypeHelper.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
61
62
63
64
65
66
67
68
69
70
71
72
var fs = require('fs'),
path = require('path'),
mime = require('mime-magic');
var getRandomName = function() {
var now = new Date();
var name = ['parasoup', now.getYear(), now.getMonth(), now.getDay(),
'-',
process.pid,
'-',
(Math.random() * 0x100000000 + 1).toString(36)].join('');
return name;
}
var getBufferMimeType = function(buffer, cb) {
var info = {
path: path.join(fs.realpathSync('/tmp'), getRandomName())
};
fs.open(info.path, 'w+', 0600, function(err, fd) {
if (err) {
cb(err);
} else {
info.fd = fd;
writeAndGetType(buffer, info, cb);
}
});
};
var writeAndGetType = function(buffer, fileinfo, cb) {
fs.write(fileinfo.fd, buffer, 0, buffer.length, 0, function(err, writter) {
if (err) {
cb(err);
} else {
getTypeAndClose(fileinfo, cb);
}
});
};
var getTypeAndClose = function(fileinfo, cb) {
try {
mime.fileWrapper(fileinfo.path, function(err, type) {
if (err) {
cb(err);
} else {
closeAndReturnType(fileinfo, type, cb);
}
});
} catch (e) {
closeDeleteAndReturnError(fileinfo, e, cb);
}
};
var closeAndDelete = function(info) {
fs.closeSync(info.fd);
fs.unlinkSync(info.path);
};
var closeAndReturnType = function(fileinfo, type, cb) {
closeAndDelete(fileinfo);
cb(null, type);
};
var closeDeleteAndReturnError = function(fileinfo, error, cb) {
closeAndDelete(fileinfo);
cb(error);
};
module.exports = {
getBufferMimeType: function(buffer, cb) {
getBufferMimeType(buffer, cb);
}
};