Skip to content

Instantly share code, notes, and snippets.

@mourner
Created November 6, 2015 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mourner/22e7f24dfa2fc1f89372 to your computer and use it in GitHub Desktop.
Save mourner/22e7f24dfa2fc1f89372 to your computer and use it in GitHub Desktop.
'use strict';
var fs = require('fs');
var path = require('path');
function lazyRead(path, chunkFn, done) {
var input = fs.createReadStream(path)
.on('readable', handleReadable)
.on('end', handleEnd);
var busy = 0;
var readable = false;
var ended = false;
function handleReadable() {
readable = true;
if (!busy) readChunk();
}
function handleEnd() {
ended = true;
if (!busy) done();
}
function chunkDone() {
if (--busy === 0) {
if (readable) readChunk();
else if (ended) done();
}
}
function readChunk() {
var chunk;
while (null !== (chunk = input.read())) {
busy++;
chunkFn(chunk, chunkDone);
}
readable = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment