-
-
Save creationix/e7bdb20003049154de9e 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
-- A simple decoder that pulls out line separated values | |
local function getLine(chunk) | |
local s, e = string.find(chunk, "[\r\n]+") | |
if not s then return end | |
return string.sub(chunk, 1, s), string.sub(chunk, e + 1) | |
end | |
-- A generic adapter for applying decoders to emitter callbacks | |
local function applyDecoder(decoder, emit) | |
local buffer = "" | |
return function (chunk) | |
buffer = buffer .. chunk | |
repeat | |
local event, more = getLine(buffer) | |
if event then | |
buffer = more | |
emit(event) | |
end | |
until not more | |
end | |
end | |
-- Sample emitter with decoder applied inline to emitter callback. | |
-- This will emit whole lines instead of raw chunks now. | |
stream:on("data", applyDecoder(getLine, function (line) | |
print(line) | |
end)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment