Talk is cheap. Show me the code。
lua读写操作很麻烦,所以暂时封装了。
阅读文件:
-阅读文件
-参数:要读取的文件的路径
-返回值:读取的内容、读取错误。
-如果未加载内容,则第一个参数为nil,否则第二个参数为nil
localfunctionread _ file (file _ name )
if not file_name then
return nil,' missing file_name '
结束
localfile=io.open(file_name,' r ' )。
if not file then
返回编号,' can' top enfile' ' . file _ name . '"
结束
local content=file : read (' * all ' ) )。
文件: close ()
返回内容,nil
结束
写文件:
-写文件
-参数:要写入的文件路径、写入内容
-返回值:写入结果
-如果内容未写入,则返回错误内容;如果内容未写入,则返回nil
本地功能write _ file (file _ name,content ) )。
if not file_name then
return nil,' missing file_name '
结束
内容=content or ' '
localfile=io.open(file_name,' a ' ) )
if not file then
return ' can' top enfile' ' . file _ name . '' '
结束
文件:写入(内容)
文件: close ()
返回Nil
结束
实战演习:
-读取和写入文件演示,写入和读取当前时间
ngx.say (' write_fileresultis : ',write _ file ) (/tmp/nowtime.log ),ngx.now ) )
ngx.say (result _ fileresultis : (,read_file ) )/tmp/nowtime.log )
-你可以这么做
本地内容,err=read_file(/tmp/tttt.log ) )。
if not content then
是NGX.say(err )
else
NGX.Say(Content ) ) ) ) ) ) ) ) )。
结束
-本机中不存在文件tttt.log,因此显示如下。
-- can't open file '/tmp/tttt.log '
截图:
image.png