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.

file.js 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. if (global.GENTLY) require = GENTLY.hijack(require);
  2. var util = require('util'),
  3. fs = require('fs'),
  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 fs.WriteStream(this.path);
  28. };
  29. File.prototype.toJSON = function() {
  30. var json = {
  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. if (this.hash && this.hash != "") {
  41. json.hash = this.hash;
  42. }
  43. return json;
  44. };
  45. File.prototype.write = function(buffer, cb) {
  46. var self = this;
  47. if (self.hash) {
  48. self.hash.update(buffer);
  49. }
  50. if (this._writeStream.closed) {
  51. return cb();
  52. }
  53. this._writeStream.write(buffer, function() {
  54. self.lastModifiedDate = new Date();
  55. self.size += buffer.length;
  56. self.emit('progress', self.size);
  57. cb();
  58. });
  59. };
  60. File.prototype.end = function(cb) {
  61. var self = this;
  62. if (self.hash) {
  63. self.hash = self.hash.digest('hex');
  64. }
  65. this._writeStream.end(function() {
  66. self.emit('end');
  67. cb();
  68. });
  69. };