njs
njs copied to clipboard
Add support for a fetch-like API for TCP (and UDP) sockets.
In a similar fashion to OpenResty's ngx.socket.tcp
My use-case for this would be for interacting (populating) Memcached directly from NJS (in a non-hack way). Of course there would be many other use-cases - for various TCP/UDP services.
Thanks for the feature. But do you know how to do TCP in current njs?
@zizifn It cannot be done properly with njs directly at present.
The hack way to do it with njs is to make a http fetch (or via a subrequest + proxy_pass) request to a local Stream Context Virtual Server that contains a js_filter script, and have that script then manipulate request into whatever the protocol should be (and likewise back-translate to response to http) - which sort of works for simple protocols - see memcached.
However, I wouldn't recommend using this approach if you have other options...
An API for talking to Unix Domain Socket would be nice as well. I was trying to replace some lua script which talks to journald (through /run/systemd/journal/socket, a SOCK_DGRAM socket) but it's not possible.
-- Error handling omitted for presentation
local sock = ngx.socket.udp()
local ok, err = sock:setpeername("unix:/run/systemd/journal/socket")
local message = "PRIORITY=5\nMESSAGE_ID=...\nMESSAGE=..."\n"
local res, err = sock:send(message)