Created
November 6, 2015 15:50
-
-
Save mourner/22e7f24dfa2fc1f89372 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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