Skip to content

Instantly share code, notes, and snippets.

@adrai
Last active August 29, 2015 14:07
Show Gist options
  • Save adrai/34c19fdd1adca9a24b9b to your computer and use it in GitHub Desktop.
Save adrai/34c19fdd1adca9a24b9b to your computer and use it in GitHub Desktop.
blob meta infos while streaming
var url = require('url');
var http = require('http');
//var imgUrl = 'http://upload.wikimedia.org/wikipedia/commons/9/95/Big_Pine_landscape.jpg';
var imgUrl = 'http://downloads.xenproject.org/Branding/Images/Mascot/Xen%20Big%20Panda%204242x3129.png';
//var imgUrl = 'http://stackoverflow.com/questions/19934406/verify-mime-type-of-uploaded-files-in-node-js';
var options = url.parse(imgUrl);
http.get(options, function (response) {
var metaCatcher = new MetaCatcher();
metaCatcher.on('meta', function (meta) {
console.log(meta);
});
metaCatcher.on('end', function() {
console.log('finished');
});
response.pipe(metaCatcher).pipe(require('fs').createWriteStream('downloaded.png'));
});
var util = require('util'),
Transform = require('stream').Transform,
mmm = require('mmmagic'),
Magic = mmm.Magic,
magic = new Magic(mmm.MAGIC_MIME_TYPE),
sizeOf = require('image-size');
function MetaCatcher (options) {
if (!(this instanceof MetaCatcher)) {
return new MetaCatcher(options);
}
Transform.call(this, options);
this.meta = { size: 0 };
this.chunks = [];
var self = this;
this.on('finish', function () {
if (self.meta.size > 0) {
self.emit('meta', self.meta);
}
});
}
util.inherits(MetaCatcher, Transform);
MetaCatcher.prototype.checkMimeType = function (callback) {
var self = this;
if (this.meta.mimeType) {
return callback();
}
magic.detect(Buffer.concat(this.chunks), function (err, result) {
if (err) {
// self.emit('error', err);
return callback();
}
self.meta.mimeType = result;
callback();
});
};
MetaCatcher.prototype.checkImageDimension = function (callback) {
if (!this.meta.mimeType) {
return callback();
}
if (this.meta.imageDimensions || (!this.meta.mimeType && this.meta.mimeType.indexOf('image') < 0)) {
this.chunks = [];
return callback();
}
try {
this.meta.imageDimensions = sizeOf(Buffer.concat(this.chunks));
this.chunks = [];
} catch (e) {
// console.log('Not ready to catch image size!!!');
}
callback();
};
MetaCatcher.prototype._transform = function (chunk, encoding, done) {
this.push(chunk);
this.chunks.push(chunk);
this.meta.size += chunk.length;
var self = this;
this.checkMimeType(function () {
self.checkImageDimension(done);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment