@adonisjs/bodyparser
Version:
AdonisJs body parser to read and parse HTTP request bodies
64 lines (63 loc) • 2.21 kB
JavaScript
;
/*
* @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.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.streamFile = void 0;
const end_of_stream_1 = __importDefault(require("end-of-stream"));
const fs_extra_1 = require("fs-extra");
/**
* 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.
*/
function streamFile(readStream, location, dataListener) {
return new Promise((resolve, reject) => {
(0, fs_extra_1.open)(location, 'w')
.then((fd) => {
/**
* Create write stream and reject promise on error
* event
*/
const writeStream = (0, fs_extra_1.createWriteStream)(location);
writeStream.on('error', reject);
/**
* Handle closing of read stream from multiple sources
*/
(0, end_of_stream_1.default)(readStream, (error) => {
(0, fs_extra_1.close)(fd);
/**
* Resolve when their are no errors in
* streaming
*/
if (!error) {
resolve();
return;
}
/**
* Otherwise cleanup write stream
*/
reject(error);
process.nextTick(() => {
writeStream.end();
(0, fs_extra_1.unlink)(writeStream.path).catch(() => { });
});
});
if (typeof dataListener === 'function') {
readStream.pause();
readStream.on('data', dataListener);
}
readStream.pipe(writeStream);
})
.catch(reject);
});
}
exports.streamFile = streamFile;