You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.5 KiB

  1. if (global.GENTLY) require = GENTLY.hijack(require);
  2. var util = require('util'),
  3. WriteStream = require('fs').WriteStream,
  4. EventEmitter = require('events').EventEmitter,
  5. crypto = require('crypto');
  6. function File(properties) {
  7. EventEmitter.call(this);
  8. this.size = 0;
  9. this.path = null;
  10. this.name = null;
  11. this.type = null;
  12. this.hash = null;
  13. this.lastModifiedDate = null;
  14. this._writeStream = null;
  15. for (var key in properties) {
  16. this[key] = properties[key];
  17. }
  18. if(typeof this.hash === 'string') {
  19. this.hash = crypto.createHash(properties.hash);
  20. } else {
  21. this.hash = null;
  22. }
  23. }
  24. module.exports = File;
  25. util.inherits(File, EventEmitter);
  26. File.prototype.open = function() {
  27. this._writeStream = new WriteStream(this.path);
  28. };
  29. File.prototype.toJSON = function() {
  30. return {
  31. size: this.size,
  32. path: this.path,
  33. name: this.name,
  34. type: this.type,
  35. mtime: this.lastModifiedDate,
  36. length: this.length,
  37. filename: this.filename,
  38. mime: this.mime
  39. };
  40. };
  41. File.prototype.write = function(buffer, cb) {
  42. var self = this;
  43. if (self.hash) {
  44. self.hash.update(buffer);
  45. }
  46. this._writeStream.write(buffer, function() {
  47. self.lastModifiedDate = new Date();
  48. self.size += buffer.length;
  49. self.emit('progress', self.size);
  50. cb();
  51. });
  52. };
  53. File.prototype.end = function(cb) {
  54. var self = this;
  55. if (self.hash) {
  56. self.hash = self.hash.digest('hex');
  57. }
  58. this._writeStream.end(function() {
  59. self.emit('end');
  60. cb();
  61. });
  62. };