使用 njs 编写脚本

njs 是 JavaScript 语言的一个子集,它允许扩展 nginx 功能。njs 是根据 ECMAScript 5.1(严格模式)创建的,带有一些 ECMAScript 6 和更高版本的扩展,它的合规性仍在不断发展。

下载&安装

作为 Linux 包安装

对于 Linux,可以使用 njs 模块包:

  • nginx-module-njs:njs 动态模块

  • nginx-module-njs-dbg:nginx-module-njs 包的调试符号

安装包后,需要使用 load_module 指令加载 njs 动态模块:

load_module modules/ngx_http_js_module.so;

或者

load_module modules/ngx_stream_js_module.so;

从源码构建

可以使用以下命令从 njs 源码存储库克隆源代码(需要 Mercurial 客户端):

hg clone http://hg.nginx.org/njs

然后使用 --add-module 配置参数从 nginx 根目录编译模块:

./configure --add-module=path-to-njs/nginx

这些模块也可以构建为动态的:

./configure --add-dynamic-module=path-to-njs/nginx

如果仅仅构建 njs 命令行实用程序,请运行 ./configure 并从 njs 根目录生成 njs 命令,该实用程序可作为 ./build/njs 使用。

用例

  • 在请求到达上游服务器之前,njs 中的复杂访问控制和安全检查

  • 操作响应头

  • 编写灵活的异步内容处理程序和过滤器

基本 HTTP 示例

在 nginx 中使用 njs:

  • 安装 njs 脚本语言

  • 创建一个 njs 脚本文件,例如 http.js:

function hello(r) {
    r.return(200, "Hello world!");
}

export default {hello};
  • 在 nginx.conf 文件中,启用 ngx_http_js_module 模块并使用 js_import 指令指定脚本文件 http.js:

load_module modules/ngx_http_js_module.so;

events {}

http {
    js_import http.js;

    server {
        listen 8000;

        location / {
            js_content http.hello;
        }
    }
}

还有一个独立的命令行实用程序,可以独立于 nginx 用于 njs 开发和调试。

可以从命令行执行 njs 脚本进行开发和调试。命令行实用程序可以在 安装 Linux 软件包 或 从源代码构建 后可用,与在 nginx 中运行的 njs 相比,nginx 对象(HTTP 和 Stream)在该实用程序中不可用。例如:

$ echo "2**3" | njs -q
8

$ njs
>> globalThis
global {
 njs: njs {
  version: '0.3.9'
 },
 global: [Circular],
 process: process {
  argv: [
   '/usr/bin/njs'
  ],
  env: {
   PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
   HOSTNAME: 'f777c149d4f8',
   TERM: 'xterm',
   NGINX_VERSION: '1.17.9',
   NJS_VERSION: '0.3.9',
   PKG_RELEASE: '1~buster',
   HOME: '/root'
  }
 },
 console: {
  log: [Function: native],
  dump: [Function: native],
  time: [Function: native],
  timeEnd: [Function: native]
 },
 print: [Function: native]
}
>>

经过测试的操作系统和平台

  • FreeBSD / amd64;

  • Linux / x86, amd64, arm64, ppc64el;

  • Solaris 11 / amd64;

  • macOS / x86_64;

说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号