UNPKG

2.21 kBJavaScriptView Raw
1"use strict";
2/*
3 * @adonisjs/bodyparser
4 *
5 * (c) Harminder Virk <virk@adonisjs.com>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10var __importDefault = (this && this.__importDefault) || function (mod) {
11 return (mod && mod.__esModule) ? mod : { "default": mod };
12};
13Object.defineProperty(exports, "__esModule", { value: true });
14exports.streamFile = void 0;
15const end_of_stream_1 = __importDefault(require("end-of-stream"));
16const fs_extra_1 = require("fs-extra");
17/**
18 * Writes readable stream to the given location by properly cleaning up readable
19 * and writable streams in case of any errors. Also an optional data listener
20 * can listen for the `data` event.
21 */
22function streamFile(readStream, location, dataListener) {
23 return new Promise((resolve, reject) => {
24 (0, fs_extra_1.open)(location, 'w')
25 .then((fd) => {
26 /**
27 * Create write stream and reject promise on error
28 * event
29 */
30 const writeStream = (0, fs_extra_1.createWriteStream)(location);
31 writeStream.on('error', reject);
32 /**
33 * Handle closing of read stream from multiple sources
34 */
35 (0, end_of_stream_1.default)(readStream, (error) => {
36 (0, fs_extra_1.close)(fd);
37 /**
38 * Resolve when their are no errors in
39 * streaming
40 */
41 if (!error) {
42 resolve();
43 return;
44 }
45 /**
46 * Otherwise cleanup write stream
47 */
48 reject(error);
49 process.nextTick(() => {
50 writeStream.end();
51 (0, fs_extra_1.unlink)(writeStream.path).catch(() => { });
52 });
53 });
54 if (typeof dataListener === 'function') {
55 readStream.pause();
56 readStream.on('data', dataListener);
57 }
58 readStream.pipe(writeStream);
59 })
60 .catch(reject);
61 });
62}
63exports.streamFile = streamFile;