ipull
Version:
The only file downloader you'll ever need. For node.js and the browser, CLI and library for fast and reliable file downloads.
57 lines • 2.11 kB
JavaScript
import BaseDownloadEngineWriteStream from "./base-download-engine-write-stream.js";
import WriterIsClosedError from "./errors/writer-is-closed-error.js";
import WriterNotDefineError from "./errors/writer-not-define-error.js";
export default class DownloadEngineWriteStreamBrowser extends BaseDownloadEngineWriteStream {
_writer;
options = {};
_memory = new Uint8Array(0);
_bytesWritten = 0;
get writerClosed() {
return this.options.file?.totalSize && this._bytesWritten === this.options.file.totalSize;
}
constructor(_writer, options = {}) {
super();
this.options = options;
this._writer = _writer;
}
_ensureBuffer(length) {
if (this._memory.length >= length) {
return this._memory;
}
if (!this.options.file) {
throw new WriterNotDefineError("Writer & file is not defined, please provide a writer or file");
}
const newSize = Math.max(length, this.options.file.totalSize);
const newMemory = new Uint8Array(newSize);
newMemory.set(this._memory);
return this._memory = newMemory;
}
write(cursor, buffers) {
if (this.writerClosed) {
throw new WriterIsClosedError();
}
if (!this._writer) {
const totalLength = buffers.reduce((sum, buffer) => sum + buffer.length, 0);
const bigBuffer = this._ensureBuffer(cursor + totalLength);
let writeLocation = cursor;
for (const buffer of buffers) {
bigBuffer.set(buffer, writeLocation);
writeLocation += buffer.length;
}
this._bytesWritten += totalLength;
return;
}
return this._writer(cursor, buffers, this.options);
}
get result() {
return this._memory;
}
resultAsBlobURL() {
const blob = new Blob([this._memory]);
return URL.createObjectURL(blob);
}
resultAsText() {
return new TextDecoder().decode(this._memory);
}
}
//# sourceMappingURL=download-engine-write-stream-browser.js.map