Openresty+Lua 讀寫文件

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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容