Automating DT with JavaScript: Shell Commands

Although JavaScript is quite powerful, some things are easier to achieve with a shell command. A simple example is downloading an HTML file or JSON data. While that’s a no-brainer if you run JavaScript in the browser, it is quite another story with JXA. It does not provide the global objects XMLHttpRequest, windownor document. So no AJAX and no DOM-Manipulation.

Back to the shell. You can run commands in it with the aptly named method doShellCommand. However, you must call it at the current application like so

const curApp = Application.currentApplication();
const result = curApp.doShellCommand('ls');

for example to get a listing of the current folder. So you need two application objects: one for DEVONthink and one for the doShellCommand call. The cool thing about JavaScript is that quoting the shell command is fairly simple. A fairly complicated example to illustrate:

const username = "your name";
let baseCMD = `sqlite3 "/Users/${username}/Library/Group Containers/5U8NS4GX82.dayoneapp2/Data/Documents/DayOne.sqlite" 'select zgregorianyear||"-"||printf("%02d",zgregorianmonth)||"-"||printf("%02d",zgregorianday) from zentry where zuuid="`;

You quote the command exactly as you would were you typing it in the terminal: use double quotes around blancs that have to be protected (here in the path to the database). Use single quotes to protect special characters like pipe symbols and double quotes, as here for the SQL command. Finally, include the whole command in backticks to protect single and double quotes. They also allow for variable expansion like in ${username}.

The command in this example retrieves the date of an entry in the DayOne journal app. It is part of a long(ish) example here

As you can see there, you can assign the output of the shell command to a variable. So,

const http = curApp.doShellCommand(`curl`);

will store the web document at in the variable http.