-
Notifications
You must be signed in to change notification settings - Fork 170
/
file.lua
50 lines (39 loc) · 1.04 KB
/
file.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
local co_yield = coroutine._yield
local co_wrap = coroutine._wrap
local open = io.open
local co_wrap_iter = require("resty.coroutines").co_wrap_iter
local chunk_size = 2^13 -- 8kb
local _M = {}
-- returns an iterator if the file is correct where can be read in chuinks of
-- 8kb.
-- If file cannot be open, it'll return nil function and the error message.
function _M.file_reader(filename)
local handle, err = open(filename)
if err then
return nil, err
end
return co_wrap_iter(function()
while true do
local chunk = handle:read(chunk_size)
if not chunk then
break
end
co_yield(chunk)
end
handle:close()
end)
end
function _M.file_size(filename)
return co_wrap(function()
local handle, err = open(filename)
if err then
return nil, err
end
local current = handle:seek()
local size = handle:seek("end")
handle:seek("set", current)
handle:close()
return size
end)
end
return _M