basant307/AI_Governance_Project
048
1/* eslint-disable no-underscore-dangle */2 3import fs from 'node:fs';4import crypto from 'node:crypto';5import { EventEmitter } from 'node:events';6 7class PersistentFile extends EventEmitter {8 constructor({ filepath, newFilename, originalFilename, mimetype, hashAlgorithm }) {9 super();10 11 this.lastModifiedDate = null;12 Object.assign(this, { filepath, newFilename, originalFilename, mimetype, hashAlgorithm });13 14 this.size = 0;15 this._writeStream = null;16 17 if (typeof this.hashAlgorithm === 'string') {18 this.hash = crypto.createHash(this.hashAlgorithm);19 } else {20 this.hash = null;21 }22 }23 24 open() {25 this._writeStream = fs.createWriteStream(this.filepath);26 this._writeStream.on('error', (err) => {27 this.emit('error', err);28 });29 }30 31 toJSON() {32 const json = {33 size: this.size,34 filepath: this.filepath,35 newFilename: this.newFilename,36 mimetype: this.mimetype,37 mtime: this.lastModifiedDate,38 length: this.length,39 originalFilename: this.originalFilename,40 };41 if (this.hash && this.hash !== '') {42 json.hash = this.hash;43 }44 return json;45 }46 47 toString() {48 return `PersistentFile: ${this.newFilename}, Original: ${this.originalFilename}, Path: ${this.filepath}`;49 }50 51 write(buffer, cb) {52 if (this.hash) {53 this.hash.update(buffer);54 }55 56 if (this._writeStream.closed) {57 cb();58 return;59 }60 61 this._writeStream.write(buffer, () => {62 this.lastModifiedDate = new Date();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 destroy() {80 this._writeStream.destroy();81 const filepath = this.filepath; 82 setTimeout(function () {83 fs.unlink(filepath, () => {});84 }, 1)85 }86}87 88export default PersistentFile;89 