Writing Alfred Workflows in Node Posted on: 2014-03-01

The problem

When creating workflows in Alfred, you're able to run a script as an action:

Run Script Action

The problem I've found is that if I want to write my script in node, the option simply isn't there:

No Node Option

The solution

I took to the Alfred forums and found a thread asking for this as a feature request. In the thread it was pointed out that there is a way to kind of "hack" it. The following is the code snippet I've come to use:

/usr/local/bin/node <<-'CODE'
try {

  var query = "{query}";

  // Node goodness here

  console.log('Whatever you want passed out of the action');

} catch (e) { console.log(e.message); }
CODE

What's the deal with that CODE bit? It's known as heredoc and lets us write a chunk of code that will get passed to (and get run by) node.

The try/catch isn't essential, but I've found that without it you won't have a clue what's gone wrong on the off chance something fails.

Lastly, I've included a variable called query that captures whatever's passed into the script from whatever precedes this action in the workflow.

Testing the script

While it's possible to write and test the script in situ as part of an Alfred workflow, it's incredibly tedious. I would recommend running the script locally and duplicating the line that receives the query so that you can put some test data in there:

/* var query = "{query}"; */
var query = "test data here";