-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathfrom.js
57 lines (49 loc) · 1.26 KB
/
from.js
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
const {statSync, createReadStream} = require('fs');
const Blob = require('./index.js');
const DOMException = require('domexception');
/**
* @param {string} path filepath on the disk
* @returns {Blob}
*/
function blobFrom(path) {
const {size, mtime} = statSync(path);
const blob = new BlobDataItem({path, size, mtime});
return new Blob([blob]);
}
/**
* This is a blob backed up by a file on the disk
* with minium requirement
*
* @private
*/
class BlobDataItem {
constructor(options) {
this.size = options.size;
this.path = options.path;
this.start = options.start;
this.mtime = options.mtime;
}
// Slicing arguments is first validated and formated
// to not be out of range by Blob.prototype.slice
slice(start, end) {
return new BlobDataItem({
path: this.path,
start,
mtime: this.mtime,
size: end - start
});
}
stream() {
if (statSync(this.path).mtime > this.mtime) {
throw new DOMException('The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.', 'NotReadableError');
}
return createReadStream(this.path, {
start: this.start,
end: this.start + this.size - 1
});
}
get [Symbol.toStringTag]() {
return 'Blob';
}
}
module.exports = blobFrom;