Skip to content

Instantly share code, notes, and snippets.

@chmanie
Last active December 28, 2015 04:19
Show Gist options
  • Save chmanie/7441515 to your computer and use it in GitHub Desktop.
Save chmanie/7441515 to your computer and use it in GitHub Desktop.
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