Last active
October 3, 2022 00:34
-
-
Save chmanie/8520572 to your computer and use it in GitHub Desktop.
Node MIME-Type checker using mmmagic. This can be used as an inspiration for more sophisticated solutions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (c) 2013 Christian Maniewski. License: MIT. | |
'use strict'; | |
var _ = require('lodash') | |
, util = require('util') | |
, stream = require('stream') | |
, Transform = stream.Transform | |
, mmm = require('mmmagic') | |
, Magic = mmm.Magic; | |
util.inherits(MimeChecker, Transform); | |
function MimeChecker(opts) { | |
Transform.call(this, opts); | |
this.data = []; | |
this.magic = new Magic(mmm.MAGIC_MIME_TYPE); | |
} | |
MimeChecker.prototype._transform = function (chunk, encoding, done) { | |
var self = this; | |
if (self.mimeFound) { | |
self.push(chunk); | |
return done(); | |
} | |
self.data.push(chunk); | |
if (self.data.length < 20) { | |
return done(); | |
} | |
else if (self.data.length === 20) { | |
self.pause(); | |
var buffered = Buffer.concat(this.data); | |
this.magic.detect(buffered, function(err, result) { | |
if (err) return self.emit('wrongmime', err); | |
// we can also allow corrupt files that most of the time turn out to be ok | |
if (!_.contains(self.getAllowedMimeTypes().concat(['application/CDFV2-corrupt']), result)) { | |
return self.emit('wrongmime', null, result); | |
} | |
self.data.map(self.push.bind(self)); | |
self.mimeFound = true; | |
self.emit('correctmime'); | |
return done(); | |
}); | |
} | |
}; | |
MimeChecker.prototype.getAllowedMimeTypes = function () { | |
// allow mp4 and webm videos only | |
return [ | |
'video/mp4', | |
'video/webm' | |
]; | |
}; | |
module.exports = MimeChecker; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var file = getFileStreamSomehow(); | |
var mimeChecker = new MimeChecker(); | |
mimeChecker.on('wrongmime', function (err, mimetype) { | |
file.unpipe(); | |
// abort the connection | |
}); | |
mimeChecker.on('correctmime', function () { | |
mimeChecker.resume(); | |
// pipe mimeChecker stream into your desired stream | |
mimeChecker.pipe(outputStream); | |
}); | |
// pipe file stream into the mimeChecker transform stream | |
file.pipe(mimeChecker); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment