1 | var mmm = require('mmmagic'),
|
2 | mime = require('mime'),
|
3 | path = require('path'),
|
4 | util = require('util'),
|
5 | common = require('../common'),
|
6 | task = require('./base');
|
7 |
|
8 | var DEFAULT_TYPE = 'application/octet-stream';
|
9 | var $global = common.$global;
|
10 |
|
11 | var MimeTask = function (cfg) {
|
12 | this.magic = new mmm.Magic(mmm.MAGIC_MIME_TYPE);
|
13 | this.init(cfg);
|
14 | };
|
15 |
|
16 | util.inherits(MimeTask, task);
|
17 |
|
18 | util.extend(MimeTask.prototype, {
|
19 | run: function () {
|
20 | if (this.filePath) {
|
21 | this.detectFile();
|
22 | } else if (this.buffer) {
|
23 | this.detectBuffer();
|
24 | } else {
|
25 | this.failed(new Error('No file path or buffer provided'));
|
26 | }
|
27 | },
|
28 |
|
29 | _onResult: function (err, mimeType) {
|
30 | if (err) {
|
31 | this.failed(err);
|
32 | } else {
|
33 | this.completed({
|
34 | type: mimeType,
|
35 | extension: mime.extensions[mimeType] ||
|
36 | mime.extensions[DEFAULT_TYPE]
|
37 | });
|
38 | }
|
39 | },
|
40 |
|
41 | detectFile: function () {
|
42 | var filePath = path.resolve ($global.project ? $global.project.root.path : '.', this.filePath);
|
43 | this.magic.detectFile (filePath, this._onResult.bind(this));
|
44 | },
|
45 |
|
46 | detectBuffer: function () {
|
47 | this.magic.detect(this.buffer, this._onResult.bind(this));
|
48 | }
|
49 | });
|
50 |
|
51 | module.exports = MimeTask;
|