Created
September 24, 2016 18:39
-
-
Save hbarcelos/c9a0c18e3e6f9fe8929968b16284aca4 to your computer and use it in GitHub Desktop.
Processing asynchronously pushed data
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
// Originally from: http://exploringjs.com/es6/ch_generators.html#_example-processing-asynchronously-pushed-data | |
'use strict' | |
const createReadStream = require('fs').createReadStream | |
function coroutine(generatorFunction) { | |
return function (...args) { | |
const generatorObject = generatorFunction(...args); | |
generatorObject.next() | |
return generatorObject | |
}; | |
} | |
function readFile(fileName, target) { | |
const readStream = createReadStream(fileName, { | |
encoding: 'utf-8', | |
bufferSize: 1024 | |
}) | |
readStream.on('data', buffer => { | |
const str = buffer.toString('utf8') | |
target.next(str) | |
}) | |
readStream.on('end', () => target.return()) | |
} | |
const splitLines = coroutine(function* (target) { | |
let previous = '' | |
try { | |
while (true) { | |
previous += yield | |
let eolIndex | |
while ((eolIndex = previous.indexOf('\n')) >= 0) { | |
const line = previous.slice(0, eolIndex) | |
target.next(line) | |
previous = previous.slice(eolIndex + 1) | |
} | |
} | |
} finally { | |
if (previous.length > 0) { | |
target.next(previous) | |
} | |
target.return() | |
} | |
}) | |
const numberLines = coroutine(function* (target) { | |
try { | |
for (let lineNo = 0; /* noop */; lineNo++) { | |
const line = yield | |
target.next(`${lineNo}: ${line}`) | |
} | |
} finally { | |
target.return() | |
} | |
}) | |
const printLines = coroutine(function* () { | |
while (true) { | |
const line = yield | |
console.log(line) | |
} | |
}) | |
// readFile(<file>, splitLines(numberLines(printLines()))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment