"use strict";
/*
 * @adonisjs/bodyparser
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.streamFile = void 0;
const util_1 = require("util");
const fs_extra_1 = require("fs-extra");
const fs_1 = require("fs");
const stream_1 = require("stream");
const pump = (0, util_1.promisify)(stream_1.pipeline);
/**
 * Writes readable stream to the given location by properly cleaning up readable
 * and writable streams in case of any errors. Also an optional data listener
 * can listen for the `data` event.
 */
async function streamFile(readStream, location, dataListener) {
    if (typeof dataListener === 'function') {
        readStream.pause();
        readStream.on('data', dataListener);
    }
    const writeStream = (0, fs_1.createWriteStream)(location);
    try {
        await pump(readStream, writeStream);
    }
    catch (error) {
        (0, fs_extra_1.unlink)(writeStream.path).catch(() => { });
        throw error;
    }
}
exports.streamFile = streamFile;
