njs 是 JavaScript 语言的一个子集,它允许扩展 nginx 功能。njs 是根据 ECMAScript 5.1(严格模式)创建的,带有一些 ECMAScript 6 和更高版本的扩展,它的合规性仍在不断发展。
对于 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 中的复杂访问控制和安全检查
操作响应头
编写灵活的异步内容处理程序和过滤器
在 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;