MCPcopy Create free account
hub / github.com/WinterTC55/iter-streams / fromNodeReadable

Function fromNodeReadable

samples/12-nodejs-interop.ts:33–62  ·  view source on GitHub ↗

* Convert a Node.js Readable stream to the new Stream API. * * Features: * - Proper backpressure handling * - Error propagation from Node.js stream to new Stream * - Cleanup on cancel (destroys the Node.js stream)

(readable: Readable)

Source from the content-addressed store, hash-verified

31 * - Cleanup on cancel (destroys the Node.js stream)
32 */
33function fromNodeReadable(readable: Readable) {
34 return Stream.from(
35 (async function* () {
36 // Track if we need to destroy the readable on cleanup
37 const destroyed = false;
38
39 try {
40 // Use async iteration (Node.js 10+)
41 for await (const chunk of readable) {
42 // Node.js streams can emit strings or Buffers
43 if (typeof chunk === 'string') {
44 yield chunk;
45 } else if (Buffer.isBuffer(chunk)) {
46 // Convert Buffer to Uint8Array (zero-copy view)
47 yield new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
48 } else if (chunk instanceof Uint8Array) {
49 yield chunk;
50 } else {
51 throw new Error(`Unexpected chunk type: ${typeof chunk}`);
52 }
53 }
54 } finally {
55 // Cleanup: destroy the readable if not already destroyed
56 if (!destroyed && !readable.destroyed) {
57 readable.destroy();
58 }
59 }
60 })()
61 );
62}
63
64// ============================================================================
65// Adapter: Create Writer that writes to Node.js Writable

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected