Re: lua内置函数的使用

332 views
Skip to first unread message
Message has been deleted
Message has been deleted

Water Duan

unread,
Jul 22, 2013, 3:52:51 AM7/22/13
to open...@googlegroups.com
proxy_pass http://127.0.0.1;
        body_filter_by_lua '
        ngx.arg[1] = os.execute("/usr/local/bin/node test.js")
        ';

打孙使用nodejs的一个脚本来替换response的body,没有成功。

ngx_lua应该如何调用外部的系统命令?

Jason Calio

unread,
Jul 22, 2013, 5:54:37 AM7/22/13
to open...@googlegroups.com
On 2013-7-22, at 下午3:52, Water Duan <lian...@dena.com> wrote:

proxy_pass http://127.0.0.1;
        body_filter_by_lua '
        ngx.arg[1] = os.execute("/usr/local/bin/node test.js")
        ';

你这里的用法有一些问题,os.execute返回值并不是命令执行的结果,而是命令执行的返回状态。见http://www.lua.org/manual/5.1/manual.html中os.execute的解释。应该用io.popen去获取命令的返回内容。

另外body_filter_by_lua中的脚本会被多次调用,见https://github.com/chaoslawful/lua-nginx-module#body_filter_by_lua

Nginx output filters may be called multiple times for a single request because response body may be delivered in chunks. Thus, the Lua code specified by in this directive may also run multiple times in the lifetime of a single HTTP request.

如果你只想替换一次的话,可以把ngx.arg[2]设置为true,这样表明替换已经执行完毕,全部内容都已经生成。

这里有一个例子,你可以参考一下。

            proxy_pass http://127.0.0.1;                                    
            body_filter_by_lua '                                                 
                local handle = assert(io.popen("ls /tmp/", "r"))                 
                local content = handle:read("*all")                              
                ngx.arg[1] = content                                             
                ngx.arg[2] = true                                                
            ';
  
打孙使用nodejs的一个脚本来替换response的body,没有成功。

ngx_lua应该如何调用外部的系统命令?


另外,在lua中使用io.popen调用外部命令会阻塞nginx进程,极大的影响nginx性能,不推荐这么做。推荐你用http协议让nginx和你的nodejs脚本通信。
--
--
邮件来自列表“openresty”,专用于技术讨论!
订阅: 请发空白邮件到 openresty...@googlegroups.com
发言: 请发邮件到 open...@googlegroups.com
退订: 请发邮件至 openresty+...@googlegroups.com
归档: http://groups.google.com/group/openresty
官网: http://openresty.org/
仓库: https://github.com/agentzh/ngx_openresty
教程: http://openresty.org/download/agentzh-nginx-tutorials-zhcn.html
 
 

Water Duan

unread,
Jul 25, 2013, 4:07:27 AM7/25/13
to open...@googlegroups.com
已可正常运行了,非常感谢~
Reply all
Reply to author
Forward
0 new messages