js-tts-wrapper
Version:
A JavaScript/TypeScript library that provides a unified API for working with multiple cloud-based Text-to-Speech (TTS) services
74 lines (73 loc) • 2.93 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.streamToBuffer = streamToBuffer;
const environment_1 = require("./environment"); // Assuming this utility exists
/**
* Reads a ReadableStream<Uint8Array> (Web) or NodeJS.ReadableStream completely
* and returns its contents as a single Buffer (in Node.js) or Uint8Array (in Browser).
* @param stream The stream to read.
* @returns A promise that resolves with the stream contents.
*/
async function streamToBuffer(stream // Use imported Readable type
) {
const chunks = []; // Use a union type for chunks array
let totalLength = 0;
// Check if it's a Web ReadableStream (has getReader)
if ("getReader" in stream && typeof stream.getReader === "function") {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
if (value) {
// value is Uint8Array from Web Stream
chunks.push(value); // Store as Uint8Array initially
totalLength += value.length;
}
}
}
finally {
reader.releaseLock();
}
// Concatenate AFTER the loop for Web Streams
if (environment_1.isNode) {
// Use isNode constant
// Convert Uint8Array chunks to Buffer before concatenating in Node
const bufferChunks = chunks.map((chunk) => Buffer.from(chunk));
return Buffer.concat(bufferChunks, totalLength);
}
// Browser environment: Concatenate Uint8Array chunks
const result = new Uint8Array(totalLength);
let offset = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
if (typeof stream.on === "function") {
// Use type assertion
// Assume it's a Node.js Readable stream
return new Promise((resolve, reject) => {
// Explicitly assert stream type for event listeners
const nodeStream = stream;
nodeStream.on("data", (chunk) => {
const bufferChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
chunks.push(bufferChunk);
totalLength += bufferChunk.length;
});
nodeStream.on("end", () => {
// Concatenate collected Buffer chunks
resolve(Buffer.concat(chunks, totalLength));
});
nodeStream.on("error", (err) => {
// Type the error parameter
reject(err);
});
});
}
// Handle unexpected stream type if it's neither Web nor Node stream
throw new Error("Unsupported stream type provided to streamToBuffer");
}
;