71 lines
1.4 KiB
JavaScript
71 lines
1.4 KiB
JavaScript
|
import util from 'util'
|
||
|
import { WriteStream } from 'fs'
|
||
|
import { EventEmitter } from 'events'
|
||
|
import crypto from 'crypto'
|
||
|
|
||
|
export default function File(properties) {
|
||
|
EventEmitter.call(this)
|
||
|
|
||
|
this.size = 0
|
||
|
this.path = null
|
||
|
this.name = null
|
||
|
this.type = null
|
||
|
this.hash = null
|
||
|
this.lastModifiedDate = null
|
||
|
|
||
|
this._writeStream = null
|
||
|
|
||
|
for (var key in properties) {
|
||
|
this[key] = properties[key]
|
||
|
}
|
||
|
|
||
|
if (typeof this.hash === 'string') {
|
||
|
this.hash = crypto.createHash(properties.hash)
|
||
|
} else {
|
||
|
this.hash = null
|
||
|
}
|
||
|
}
|
||
|
|
||
|
util.inherits(File, EventEmitter)
|
||
|
|
||
|
File.prototype.open = function() {
|
||
|
this._writeStream = new WriteStream(this.path)
|
||
|
}
|
||
|
|
||
|
File.prototype.toJSON = function() {
|
||
|
return {
|
||
|
size: this.size,
|
||
|
path: this.path,
|
||
|
name: this.name,
|
||
|
type: this.type,
|
||
|
mtime: this.lastModifiedDate,
|
||
|
length: this.length,
|
||
|
filename: this.filename,
|
||
|
mime: this.mime
|
||
|
}
|
||
|
}
|
||
|
|
||
|
File.prototype.write = function(buffer, cb) {
|
||
|
var self = this
|
||
|
if (self.hash) {
|
||
|
self.hash.update(buffer)
|
||
|
}
|
||
|
this._writeStream.write(buffer, function() {
|
||
|
self.lastModifiedDate = new Date()
|
||
|
self.size += buffer.length
|
||
|
self.emit('progress', self.size)
|
||
|
cb()
|
||
|
})
|
||
|
}
|
||
|
|
||
|
File.prototype.end = function(cb) {
|
||
|
var self = this
|
||
|
if (self.hash) {
|
||
|
self.hash = self.hash.digest('hex')
|
||
|
}
|
||
|
this._writeStream.end(function() {
|
||
|
self.emit('end')
|
||
|
cb()
|
||
|
})
|
||
|
}
|