Talk is cheap. Show me the code.
因為 lua 寫讀寫操作比較麻煩,所以大致封裝了一下。
讀文件:
-- 讀文件
-- 參數(shù):需要讀取的文件路徑
-- 返回值:讀出的內容,讀取錯誤。
-- 如果沒有讀出內容,第一個參數(shù)為 nil,否則第二個參數(shù)為 nil
local function read_file(file_name)
if not file_name then
return nil, "missing file_name"
end
local file = io.open(file_name,'r')
if not file then
return nil, "can\'t open file \"" .. file_name .. "\""
end
local content = file:read('*all')
file:close()
return content, nil
end
寫文件:
-- 寫文件
-- 參數(shù):需要寫入的文件路徑,寫入內容
-- 返回值:寫入結果
-- 如果沒有寫入內容,返回錯誤內容,否則返回 nil
local function write_file(file_name, content)
if not file_name then
return nil, "missing file_name"
end
content = content or ''
local file = io.open(file_name, "a")
if not file then
return "can\'t open file \"" .. file_name .. "\""
end
file:write(content)
file:close()
return nil
end
實戰(zhàn)演練:
-- 讀寫文件演示,寫入當前時間,再讀取出來
ngx.say("write_file result is: ", write_file("/tmp/nowtime.log", ngx.now()))
ngx.say("result_file result is: ", read_file("/tmp/nowtime.log"))
-- 也可以這樣
local content, err = read_file("/tmp/tttt.log")
if not content then
ngx.say(err)
else
ngx.say(content)
end
-- 本機不存在文件 tttt.log,所以顯示:
-- can't open file "/tmp/tttt.log"
截圖:

image.png