Search code examples
javascriptmacoscocoaautomatorjavascript-automation

How to Launch Asynchronous Background Process in JXA


I'm trying to get an HTTP server running from a JXA (JavaScript for Automation) Mac app. This part is easy as easy as:

app.doShellScript("python -m SimpleHTTPServer");

(More info here: https://github.com/JXA-Cookbook/JXA-Cookbook/wiki/Shell-and-CLI-Interactions)

The problem is, after you've done that, the application process halts because the shell script doesn't actually quit.

Well then ... we just need to make the server run as a background process right?. Unfortunately, none of the things I've tried have transferred control back to the JXA app.

Here's what I've tried:

  1. app.doShellScript("nohup python -m SimpleHTTPServer > /dev/null <&- >&- 2>&- & disown");
  2. app.doShellScript("( python -m SimpleHTTPServer > /dev/null & )");
  3. $.system("( python -m SimpleHTTPServer & )");
  4. Wrote a python script that would launch another process that runs the server and quits
  5. Tried the same thing in Node.js
  6. Tried a shell script that would launch the server and end with exit 0
  7. Tried firing up a cron job that would launch the shell script immediately that would launch the server, but it appears there are sandboxing issues with CRON.
  8. Various hacks with $.NSTask

It seems that the eventual solution will involve the background process being launch in a way that is completely 100% zero-knowledge detached from the JXA application.


Solution

  • So after a system reboot, it turns out this works:

    $.system("nohup python -m SimpleHTTPServer > /dev/null &");
    console.log("Non-blocking!");
    

    (Thank you StackOverflow for being my rubber duck.)