1 | "use strict";
|
2 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
3 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
4 | };
|
5 | const assert_1 = __importDefault(require("assert"));
|
6 | const fs_extra_1 = __importDefault(require("fs-extra"));
|
7 | const multistream_1 = __importDefault(require("multistream"));
|
8 | const path_1 = __importDefault(require("path"));
|
9 | const async_sema_1 = __importDefault(require("async-sema"));
|
10 | const semaToPreventEMFILE = new async_sema_1.default(20);
|
11 | class FileFsRef {
|
12 | constructor({ mode = 0o100644, contentType, fsPath }) {
|
13 | assert_1.default(typeof mode === 'number');
|
14 | assert_1.default(typeof fsPath === 'string');
|
15 | this.type = 'FileFsRef';
|
16 | this.mode = mode;
|
17 | this.contentType = contentType;
|
18 | this.fsPath = fsPath;
|
19 | }
|
20 | static async fromFsPath({ mode, contentType, fsPath, }) {
|
21 | let m = mode;
|
22 | if (!m) {
|
23 | const stat = await fs_extra_1.default.lstat(fsPath);
|
24 | m = stat.mode;
|
25 | }
|
26 | return new FileFsRef({ mode: m, contentType, fsPath });
|
27 | }
|
28 | static async fromStream({ mode = 0o100644, contentType, stream, fsPath, }) {
|
29 | assert_1.default(typeof mode === 'number');
|
30 | assert_1.default(typeof stream.pipe === 'function');
|
31 | assert_1.default(typeof fsPath === 'string');
|
32 | await fs_extra_1.default.mkdirp(path_1.default.dirname(fsPath));
|
33 | await new Promise((resolve, reject) => {
|
34 | const dest = fs_extra_1.default.createWriteStream(fsPath, {
|
35 | mode: mode & 0o777,
|
36 | });
|
37 | stream.pipe(dest);
|
38 | stream.on('error', reject);
|
39 | dest.on('finish', resolve);
|
40 | dest.on('error', reject);
|
41 | });
|
42 | return new FileFsRef({ mode, contentType, fsPath });
|
43 | }
|
44 | async toStreamAsync() {
|
45 | await semaToPreventEMFILE.acquire();
|
46 | const release = () => semaToPreventEMFILE.release();
|
47 | const stream = fs_extra_1.default.createReadStream(this.fsPath);
|
48 | stream.on('close', release);
|
49 | stream.on('error', release);
|
50 | return stream;
|
51 | }
|
52 | toStream() {
|
53 | let flag = false;
|
54 |
|
55 | return multistream_1.default(cb => {
|
56 | if (flag)
|
57 | return cb(null, null);
|
58 | flag = true;
|
59 | this.toStreamAsync()
|
60 | .then(stream => {
|
61 | cb(null, stream);
|
62 | })
|
63 | .catch(error => {
|
64 | cb(error, null);
|
65 | });
|
66 | });
|
67 | }
|
68 | }
|
69 | module.exports = FileFsRef;
|