Last active
December 28, 2015 04:19
-
-
Save chmanie/7441515 to your computer and use it in GitHub Desktop.
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 util = require('util') | |
, fs = require('fs') | |
, stream = require('stream') | |
, mmm = require('mmmagic') | |
, Magic = mmm.Magic; | |
var mimeChecker = new stream.Transform(); | |
mimeChecker.data = []; | |
mimeChecker.mimeFound = false; | |
mimeChecker._transform = function (chunk, encoding, done) { | |
var self = this; | |
if (this.data.length < 10) { | |
this.data.push(chunk); | |
done(); | |
} | |
else if (this.data.length === 10 && !this.mimeFound) { | |
var buffered = Buffer.concat(this.data); | |
new Magic(mmm.MAGIC_MIME_TYPE).detect(buffered, function(err, result) { | |
if (err) return self.emit('error', err); | |
if (result === 'text/plain') { | |
return self.emit('error', new Error('Wrong MIME type')); | |
} else { | |
self.data.map(self.push.bind(self)); // re-emit all buffered data! | |
self.mimeFound = true; | |
} | |
done(); | |
}); | |
} | |
else { | |
this.push(chunk); | |
done(); | |
} | |
}; | |
var inputFile = fs.createReadStream('somefile.nottxt'); | |
var checkedFile = mimeChecker; | |
checkedFile.on('error', function (err) { | |
console.log(err); | |
}); | |
var outputFile = fs.createWriteStream('someotherfile.nottxt'); | |
inputFile.pipe(checkedFile).pipe(outputFile); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment