UNPKG

extract-base-iterator

Version:

Base iterator for extract iterators like tar-iterator and zip-iterator

35 lines (34 loc) 1.01 kB
/** * Read entire stream content as string * * Handles both flowing streams and streams that have already * buffered data (using readable stream semantics). * * Node 0.8+ compatible. */ import oo from 'on-one'; import { bufferFrom } from './compat.js'; export default function streamToString(stream, callback) { const chunks = []; // Handle data from the stream stream.on('data', (chunk)=>{ if (typeof chunk === 'string') { chunks.push(bufferFrom(chunk, 'utf8')); } else { chunks.push(chunk); } }); // Handle stream end events using on-one for Node 0.8 compatibility oo(stream, [ 'error', 'end', 'close' ], (err)=>{ if (err) return callback(err); const content = Buffer.concat(chunks).toString('utf8'); callback(undefined, content); }); // Ensure stream is flowing (in case it's paused) if (typeof stream.resume === 'function') { stream.resume(); } }