Skip to content

Commit

Permalink
Added option to calculate checksums for incoming files
Browse files Browse the repository at this point in the history
  • Loading branch information
sreuter authored and felixge committed Jun 4, 2012
1 parent bcaa95d commit d2497a4
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
4 changes: 4 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,10 @@ Limits the amount of memory a field (not file) can allocate in bytes.
If this value is exceeded, an `'error'` event is emitted. The default
size is 2MB.

__incomingForm.hash = false__

If you want checksums calculated for incoming files, set this to either `'sha1'` or `'md5'`.

__incomingForm.bytesReceived__

The amount of bytes received for this form so far.
Expand Down
21 changes: 17 additions & 4 deletions lib/file.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ if (global.GENTLY) require = GENTLY.hijack(require);

var util = require('./util'),
WriteStream = require('fs').WriteStream,
EventEmitter = require('events').EventEmitter;
EventEmitter = require('events').EventEmitter,
crypto = require('crypto')

function File(properties) {
EventEmitter.call(this);
Expand All @@ -14,9 +15,15 @@ function File(properties) {
this.lastModifiedDate = null;

this._writeStream = null;

for (var key in properties) {
this[key] = properties[key];

if(typeof properties === 'object') {
if(typeof properties.hash === 'string') {
this.hash = crypto.createHash(properties.hash);
}
delete(properties.hash);
for (var key in properties) {
this[key] = properties[key];
}
}

this._backwardsCompatibility();
Expand Down Expand Up @@ -45,6 +52,9 @@ File.prototype.open = function() {
File.prototype.write = function(buffer, cb) {
var self = this;
this._writeStream.write(buffer, function() {
if(self.hash) {
self.hash.update(buffer);
}
self.lastModifiedDate = new Date();
self.size += buffer.length;
self.emit('progress', self.size);
Expand All @@ -55,6 +65,9 @@ File.prototype.write = function(buffer, cb) {
File.prototype.end = function(cb) {
var self = this;
this._writeStream.end(function() {
if(self.hash) {
self.hash = self.hash.digest('hex');
}
self.emit('end');
cb();
});
Expand Down
2 changes: 2 additions & 0 deletions lib/incoming_form.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ function IncomingForm() {
this.encoding = 'utf-8';
this.headers = null;
this.type = null;
this.hash = false;

this.bytesReceived = null;
this.bytesExpected = null;
Expand Down Expand Up @@ -188,6 +189,7 @@ IncomingForm.prototype.handlePart = function(part) {
path: this._uploadPath(part.filename),
name: part.filename,
type: part.mime,
hash: self.hash
});

this.emit('fileBegin', part.name, file);
Expand Down

0 comments on commit d2497a4

Please sign in to comment.