-
-
Notifications
You must be signed in to change notification settings - Fork 688
Expand file tree
/
Copy pathPersistentFile.js
More file actions
100 lines (86 loc) · 1.99 KB
/
Copy pathPersistentFile.js
File metadata and controls
100 lines (86 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* eslint-disable no-underscore-dangle */
import fs from "node:fs";
import crypto from "node:crypto";
import { EventEmitter } from "node:events";
class PersistentFile extends EventEmitter {
constructor({
filepath,
newFilename,
originalFilename,
mimetype,
hashAlgorithm,
}) {
super();
this.lastModifiedDate = null;
Object.assign(this, {
filepath,
newFilename,
originalFilename,
mimetype,
hashAlgorithm,
});
this.size = 0;
this._writeStream = null;
if (typeof this.hashAlgorithm === "string") {
this.hash = crypto.createHash(this.hashAlgorithm);
} else {
this.hash = null;
}
}
open() {
this._writeStream = fs.createWriteStream(this.filepath);
this._writeStream.on("error", (err) => {
this.emit("error", err);
});
}
toJSON() {
const json = {
size: this.size,
filepath: this.filepath,
newFilename: this.newFilename,
mimetype: this.mimetype,
mtime: this.lastModifiedDate,
length: this.length,
originalFilename: this.originalFilename,
};
if (this.hash && this.hash !== "") {
json.hash = this.hash;
}
return json;
}
toString() {
return `PersistentFile: ${this.newFilename}, Original: ${this.originalFilename}, Path: ${this.filepath}`;
}
write(buffer, cb) {
if (this.hash) {
this.hash.update(buffer);
}
if (this._writeStream.closed) {
cb();
return;
}
this._writeStream.write(buffer, () => {
this.lastModifiedDate = new Date();
this.size += buffer.length;
this.emit("progress", this.size);
cb();
});
}
end(cb) {
if (this.hash) {
this.hash = this.hash.digest("hex");
}
this._writeStream.end(() => {
this.emit("end");
cb();
});
}
destroy() {
this._writeStream.destroy();
const { filepath } = this;
setTimeout(() => {
fs.unlink(filepath, () => {});
}, 1);
}
}
export default PersistentFile;