njs、nginx JavaScript、在nginx上写JavaScript、nginx支持js
现在是 2024-08-05 ,在一个月前,我逛nginx官网,还没有这个模块的介绍。看njs官网,在四年前已经创建这个项目。不知道是不是近期才把这个项目纳入。以前不知道这模块,傻傻去学lua了,lua模块对于我有些上手难度,远远没有JavaScript容易。
- njs模块官网:https://github.com/nginx/njs
 
NGINX JavaScript,也称为NJS,是NGINX的动态模块,它支持使用熟悉的JavaScript语法扩展内置功能。NJS语言是JavaScript的一个子集,与ES5(ECMAScript 5.1 Strict Variant)兼容,具有一些ES6(ECMAScript 6)和更新的扩展。
一、编译安装
环境centos 7服务器。
下载当前最新的源码(2024-08-05,nginx最新1.27.0,njs最新0.8.5):
wget https://nginx.org/download/nginx-1.27.0.tar.gz
wget https://github.com/nginx/njs/archive/refs/tags/0.8.5.tar.gz
# 解压
tar -zxf nginx-1.27.0.tar.gz
tar -zxf 0.8.5.tar.gz
# /root/lk/temp/jsnginx/nginx-1.27.0
# /root/lk/temp/jsnginx/njs-0.8.5
# 安装所需依赖库
yum -y install libxml2 libxslt libxslt-devel
# 安装模块
cd nginx-1.27.0
./configure --add-dynamic-module=/root/lk/temp/jsnginx/njs-0.8.5/nginx
# 注意,如果你要使用 njs 与 NGINX Stream ,应该使用下面的命令
# ./configure --with-stream --add-dynamic-module=/root/lk/temp/jsnginx/njs-0.8.5/nginx
# 编译安装
make install
注意,路径输出均使用默认的:
  nginx path prefix: "/usr/local/nginx"
  nginx binary file: "/usr/local/nginx/sbin/nginx"
  nginx modules path: "/usr/local/nginx/modules"
  nginx configuration prefix: "/usr/local/nginx/conf"
  nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
  nginx pid file: "/usr/local/nginx/logs/nginx.pid"
  nginx error log file: "/usr/local/nginx/logs/error.log"
  nginx http access log file: "/usr/local/nginx/logs/access.log"
启动nginx
sudo /usr/local/nginx/sbin/nginx
访问没毛病:192.168.247.129

二、编写JavaScript
2.1 hello word
第一步 hello word
mkdir -p /etc/nginx/njs
cd /etc/nginx/njs
vi hello.js
hello.js 内容如下
function hello(r) {
  // 设置响应头
  r.headersOut['Content-Type']="text/html;charset=utf-8";
  r.return(200, "Hello world!\n");
}
export default {hello}
修改配置 vi /usr/local/nginx/conf/nginx.conf 整体内容如下
#user  nobody;
worker_processes  1;
#pid        logs/nginx.pid;
# 加载模块,添加模块需要在 events 之前添加
load_module /usr/local/nginx/modules/ngx_http_js_module.so;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
   # js 路径
   js_path "/etc/nginx/njs/";
   # 导入我们的js
   js_import hellojs from hello.js;
    server {
        listen       80;
        server_name  localhost;
       location / {
         # 直接返回内容
         js_content hellojs.hello;
       }
    }
}
PS: 可以直接复制替换
重启nginx:
cd /usr/local/nginx/sbin
# 重载配置
./nginx -s reload
访问正常:

2.2 其他
更多参考文献,JavaScript用法,请参考nginx官网:
https://nginx.org/en/docs/njs/reference.html