Conditional loading (#104)

use good old cjs to conditionally load stuff in node only
This commit is contained in:
Jimmy Wärting
2021-07-16 00:33:00 +02:00
committed by GitHub
parent 701103ffd2
commit 52f296c283
2 changed files with 38 additions and 33 deletions
+4 -33
View File
@@ -1,39 +1,11 @@
// TODO (jimmywarting): in the feature use conditional loading with top level await (requires 14.x)
// Node has recently added whatwg stream into core, want to use that instead when it becomes avalible.
// Node has recently added whatwg stream into core, want to use that instead when it becomes available.
import * as stream from 'web-streams-polyfill/dist/ponyfill.es2018.js'
const ReadableStream = globalThis.ReadableStream || stream.ReadableStream
const ByteLengthQueuingStrategy = globalThis.ByteLengthQueuingStrategy || stream.ReadableStream
import './streams.cjs';
/** @typedef {import('buffer').Blob} NodeBlob} */
// Fix buffer.Blob's missing stream implantation
import('buffer').then(m => {
if (m.Blob && !m.Blob.prototype.stream) {
m.Blob.prototype.stream = function name(params) {
let position = 0;
const blob = this;
const stratergy = new ByteLengthQueuingStrategy({ highWaterMark: POOL_SIZE });
return new ReadableStream({
type: "bytes",
async pull(ctrl) {
const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE));
const buffer = await chunk.arrayBuffer();
position += buffer.byteLength;
ctrl.enqueue(new Uint8Array(buffer))
if (position === blob.size) {
ctrl.close()
}
}
}, stratergy)
}
}
}, () => {})
// 64 KiB (same size chrome slice theirs blob into Uint8array's)
const POOL_SIZE = 65536;
@@ -171,15 +143,14 @@ export default class Blob {
stream() {
const it = toIterator(this.#parts, true);
const stratergy = new ByteLengthQueuingStrategy({ highWaterMark: POOL_SIZE });
return new ReadableStream({
type: "bytes",
type: 'bytes',
async pull(ctrl) {
const chunk = await it.next();
chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value);
}
}, stratergy)
})
}
/**
+34
View File
@@ -0,0 +1,34 @@
// 64 KiB (same size chrome slice theirs blob into Uint8array's)
const POOL_SIZE = 65536;
if (!globalThis.ReadableStream) {
try {
Object.assign(globalThis, require('streasm/web'))
} catch (error) {
Object.assign(globalThis, require('web-streams-polyfill/dist/ponyfill.es2018.js'))
}
}
try {
const {Blob} = require('buffer')
if (Blob && !Blob.prototype.stream) {
Blob.prototype.stream = function name(params) {
let position = 0;
const blob = this;
return new ReadableStream({
type: 'bytes',
async pull(ctrl) {
const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE));
const buffer = await chunk.arrayBuffer();
position += buffer.byteLength;
ctrl.enqueue(new Uint8Array(buffer))
if (position === blob.size) {
ctrl.close()
}
}
})
}
}
} catch (error) {}