diff --git a/lib/index.js b/lib/index.js index bd18a4b..acb5b59 100644 --- a/lib/index.js +++ b/lib/index.js @@ -2,6 +2,30 @@ var Magic = require('../build/Release/magic'); var fbpath = require('path').join(__dirname, '..', 'magic', 'magic'); Magic.setFallback(fbpath); +Magic.Magic.prototype.detectFileAsync = function(path) { + return new Promise((resolve, reject) => { + this.detectFile(path, (err, result) => { + if (err) { + return reject(err) + } + + resolve(result) + }) + }) +} + +Magic.Magic.prototype.detectAsync = function(buffer) { + return new Promise((resolve, reject) => { + this.detect(buffer, (err, mimeType) => { + if (err) { + return reject(err) + } + + resolve(mimeType) + }) + }) +} + module.exports = { Magic: Magic.Magic, MAGIC_NONE: 0x000000, /* No flags (default for Windows) */ diff --git a/test/test.js b/test/test.js index 934b011..051f6b0 100644 --- a/test/test.js +++ b/test/test.js @@ -98,6 +98,32 @@ var tests = [ }, what: 'detect - Normal operation, mime type' }, + { run: function() { + var magic = new mmm.Magic(mmm.MAGIC_MIME_TYPE); + magic.detectFileAsync(path.join(__dirname, '..', 'src', 'binding.cc')) + .then(result => { + assert.strictEqual(result, 'text/x-c++'); + next(); + }); + }, + what: 'detectFileAsync - Normal operation' + }, + { run: function() { + var magic = new mmm.Magic(mmm.MAGIC_MIME_TYPE); + assert.rejects(magic.detectFileAsync('/no/such/path1234567')).then(next); + }, + what: 'detectFileAsync - Error' + }, + { run: function() { + var buf = fs.readFileSync(path.join(__dirname, '..', 'src', 'binding.cc')); + var magic = new mmm.Magic(mmm.MAGIC_MIME_TYPE); + magic.detectAsync(buf).then(result => { + assert.strictEqual(result, 'text/x-c++'); + next(); + }); + }, + what: 'detectAsync - Normal operation' + } ]; function next() {