jow- / ucode

JavaScript-like language with optional templating
ISC License
87 stars 24 forks source link

Using uloop to read continuous output from an external program #119

Closed huafu closed 1 year ago

huafu commented 1 year ago

I'm trying to read continuous output from a program (like tail -f), calling a function each time there is a new line in the stdout of that program, and I can't figure out the right way to do it. I suppose I should use uloop.task() but I'm not even sure that's the right way to do it.

I was think of having an external shell script publishing an event to ubus each time there is new data, but I'd like to avoid having data going thru ubus when it can be avoided, and also I feel that's a hacky way of doing such thing...

The program is mosquitto_sub, but you can actually think of it as a tail -f /some/file.

I'd like to have a ucode function called each time there is a new line of output from that program (but within the same ucode process of course), the argument of that function being the outputed line. How should I achieve this?

Thanks in advance for the tips/help

jow- commented 1 year ago

The following minimal example works for me:

# Terminal 1 - producer:
while true; do date +%s >> /tmp/tail.txt; sleep 1; done
# Terminal 2 - ucode consumer:
ucode -luloop -lfs -e '
  tailf = fs.popen("tail -f /tmp/tail.txt");

  uloop.init();
  uloop.handle(tailf, (ev) => printf(`Line: ${trim(tailf.read("line"))}\n`), uloop.ULOOP_READ);
  uloop.run();
'
huafu commented 1 year ago

Hi @jow- , thanks for your quick answer again!