UNPKG

whatwg-streams-impl

Version:

WHATWG Streams Implementation for Node.JS

76 lines (64 loc) 1.57 kB
const {ReadableStream} = require('./lib/index'); const src = [1, 2, 3, 4, 5, 6, 7, 8]; const nodeReadableStream = new require('stream').Readable({ read() { if (src.length > 0) { this.push(String(src.shift())); } else { this.push(null); } } }); /* const stream = new ReadableStream({ start(controller) { console.log('underlyingSource.start() called.'); }, pull(controller) { console.log('underlyingSource.pull() called.'); if (src.length > 0) { controller.enqueue(src.shift()); } else { controller.close(); } }, cancel(reason) { console.log('underlyingSource.cancel() called. Reason:', reason); } }); */ const stream = new ReadableStream({ start(controller) { nodeReadableStream.pause(); nodeReadableStream.on('data', (chunk) => { controller.enqueue(chunk); nodeReadableStream.pause(); }); nodeReadableStream.once('end', () => controller.close()); nodeReadableStream.once('error', (e) => controller.error(e)); }, pull(controller) { nodeReadableStream.resume(); }, cancel() { nodeReadableStream.destroy(); } }); const reader = stream.getReader(); async function read() { let value; let done = false; while (!done) { ({value, done} = await reader.read()); console.log('Read:', value, done); // Do something with value, if `done` is still not `true` } // Finished reading. Do something console.log('finished'); } async function run() { await read(); console.log('all done'); console.log(reader); } run();