@rsksmart/rif-storage
Version:
Library integrating distributed storage projects
67 lines (66 loc) • 2.05 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const readable_stream_1 = require("readable-stream");
// Taken from https://github.com/JCCR/web-streams-node
// License: https://github.com/jccr/web-streams-node/blob/master/LICENSE
class NodeReadable extends readable_stream_1.Readable {
constructor(webStream, options) {
super(options);
this._webStream = webStream;
this._reader = webStream.getReader();
this._reading = false;
this._doneReading = undefined;
}
_read() {
if (this._reading) {
return;
}
this._reading = true;
const doRead = () => {
this._reader.read().then(res => {
if (this._doneReading) {
this._reading = false;
this._reader.releaseLock();
this._doneReading();
}
if (res.done) {
this.push(null);
this._reading = false;
this._reader.releaseLock();
return;
}
if (this.push(res.value)) {
return doRead();
}
else {
this._reading = false;
}
});
};
doRead();
}
_destroy(err, callback) {
if (this._reading) {
const promise = new Promise(resolve => {
this._doneReading = resolve;
});
promise.then(() => this._handleDestroy(err, callback));
}
else {
this._handleDestroy(err, callback);
}
}
_handleDestroy(err, callback) {
this._webStream.cancel();
super._destroy(err, callback);
}
}
function isNodeReadable(stream) {
return stream[Symbol.asyncIterator] !== undefined;
}
function normalizeStream(stream) {
if (isNodeReadable(stream))
return stream;
return new NodeReadable(stream);
}
exports.default = normalizeStream;