Skip to content

Commit

Permalink
Clean up read stream a little
Browse files Browse the repository at this point in the history
  • Loading branch information
creationix committed Oct 12, 2011
1 parent 31763dc commit 1c2a7fd
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
6 changes: 3 additions & 3 deletions examples/fs-streams.lua
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ stream:on('end', function ()
p("on_end")
end)

print("Adding closed listener")
stream:on('closed', function ()
p("on_closed")
print("Adding close listener")
stream:on('close', function ()
p("on_close")
end)
9 changes: 5 additions & 4 deletions lib/fs.lua
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ local CHUNK_SIZE = 65536
local read_options = {
flags = "r",
mode = "0644",
chunk_size = CHUNK_SIZE,
offset = 0,
length = nil -- nil means read to EOF
}
Expand All @@ -55,19 +56,18 @@ function FS.create_read_stream(path, options)
if err then return stream:emit("error", err) end
local offset = options.offset
local last = options.length and offset + options.length
p({offset=offset,last=last,length=options.length})
local chunk_size = options.chunk_size

local function read_chunk()
local to_read = (last and CHUNK_SIZE + offset > last and last - offset) or CHUNK_SIZE
local to_read = (last and chunk_size + offset > last and last - offset) or chunk_size
FS.read(fd, offset, to_read, function (err, chunk, len)
if err or len == 0 then
FS.close(fd, function (err)
if err then return stream:emit("error", err) end
stream:emit("close")
end)
if err then return stream:emit("error", err) end
end
if len == 0 then

stream:emit("end")
else
stream:emit("data", chunk, len)
Expand All @@ -84,6 +84,7 @@ end
local write_options = {
flags = "w",
mode = "0644",
chunk_size = CHUNK_SIZE,
offset = 0,
}
local write_meta = {__index=write_options}
Expand Down

0 comments on commit 1c2a7fd

Please sign in to comment.