Skip to content

Instantly share code, notes, and snippets.

@creationix
Last active August 29, 2015 14:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creationix/e7bdb20003049154de9e to your computer and use it in GitHub Desktop.
Save creationix/e7bdb20003049154de9e to your computer and use it in GitHub Desktop.
-- 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