basant307/AI_Governance_Project
048
1/* eslint-disable no-underscore-dangle */2 3import { createHash } from 'node:crypto';4import { EventEmitter } from 'node:events';5 6class VolatileFile extends EventEmitter {7 constructor({ filepath, newFilename, originalFilename, mimetype, hashAlgorithm, createFileWriteStream }) {8 super();9 10 this.lastModifiedDate = null;11 Object.assign(this, { filepath, newFilename, originalFilename, mimetype, hashAlgorithm, createFileWriteStream });12 13 this.size = 0;14 this._writeStream = null;15 16 if (typeof this.hashAlgorithm === 'string') {17 this.hash = createHash(this.hashAlgorithm);18 } else {19 this.hash = null;20 }21 }22 23 open() {24 this._writeStream = this.createFileWriteStream(this);25 this._writeStream.on('error', (err) => {26 this.emit('error', err);27 });28 }29 30 destroy() {31 this._writeStream.destroy();32 }33 34 toJSON() {35 const json = {36 size: this.size,37 newFilename: this.newFilename,38 length: this.length,39 originalFilename: this.originalFilename,40 mimetype: this.mimetype,41 };42 if (this.hash && this.hash !== '') {43 json.hash = this.hash;44 }45 return json;46 }47 48 toString() {49 return `VolatileFile: ${this.originalFilename}`;50 }51 52 write(buffer, cb) {53 if (this.hash) {54 this.hash.update(buffer);55 }56 57 if (this._writeStream.closed || this._writeStream.destroyed) {58 cb();59 return;60 }61 62 this._writeStream.write(buffer, () => {63 this.size += buffer.length;64 this.emit('progress', this.size);65 cb();66 });67 }68 69 end(cb) {70 if (this.hash) {71 this.hash = this.hash.digest('hex');72 }73 this._writeStream.end(() => {74 this.emit('end');75 cb();76 });77 }78}79 80export default VolatileFile;81 