Skip to content

Instantly share code, notes, and snippets.

@hbarcelos
Created September 24, 2016 18:39
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 hbarcelos/c9a0c18e3e6f9fe8929968b16284aca4 to your computer and use it in GitHub Desktop.
Save hbarcelos/c9a0c18e3e6f9fe8929968b16284aca4 to your computer and use it in GitHub Desktop.
Processing asynchronously pushed data
// 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