W3cubDocs

/nginx

Module ngx_stream_js_module

The ngx_stream_js_module module is used to implement handlers in njs — a subset of the JavaScript language.

This module is not built by default. Download and install instructions are available here.

Example Configuration

load_module modules/ngx_stream_js_module.so;
...

stream {
    js_include stream.js;

    js_set $bar bar;
    js_set $req_line req_line;

    server {
        listen 12345;

        js_preread preread;
        return     $req_line;
    }

    server {
        listen 12346;

        js_access  access;
        proxy_pass 127.0.0.1:8000;
        js_filter  header_inject;
    }
}

http {
    server {
        listen 8000;
        location / {
            return 200 $http_foo\n;
        }
    }
}

The stream.js file:

var line = '';

function bar(s) {
    var v = s.variables;
    s.log("hello from bar() handler!");
    return "bar-var" + v.remote_port + "; pid=" + v.pid;
}

function preread(s) {
    s.on('upload', function (data, flags) {
        var n = data.indexOf('\n');
        if (n != -1) {
            line = data.substr(0, n);
            s.done();
        }
    });
}

function req_line(s) {
    return line;
}

// Read HTTP request line.
// Collect bytes in 'req' until
// request line is read.
// Injects HTTP header into a client's request

var my_header =  'Foo: foo';
function header_inject(s) {
    var req = '';
    s.on('upload', function(data, flags) {
        req += data;
        var n = req.search('\n');
        if (n != -1) {
            var rest = req.substr(n + 1);
            req = req.substr(0, n + 1);
            s.send(req + my_header + '\r\n' + rest, flags);
            s.off('upload');
        }
    });
}

function access(s) {
    if (s.remoteAddress.match('^192.*')) {
        s.abort();
        return;
    }

    s.allow();
}

Directives

Syntax: js_access function;
Default:
Context: stream, server

Sets an njs function which will be called at the access phase.

Syntax: js_filter function;
Default:
Context: stream, server

Sets a data filter.

Syntax: js_include file;
Default:
Context: stream

Specifies a file that implements server and variable handlers in njs.

Syntax: js_path path;
Default:
Context: http

This directive appeared in version 0.3.0.

Sets an additional path for njs modules.

Syntax: js_preread function;
Default:
Context: stream, server

Sets an njs function which will be called at the preread phase.

Syntax: js_set $variable function;
Default:
Context: stream

Sets an njs function for the specified variable.

Session Object Properties

Each stream njs handler receives one argument, a stream session object.

© 2002-2019 Igor Sysoev
© 2011-2019 Nginx, Inc.
Licensed under the BSD License.
https://nginx.org/en/docs/stream/ngx_stream_js_module.html