Sunday, December 28, 2014

Passing multiple parameters from AppleScript to Node.js Server

Most previous solutions to moving data from AppleScript to a server on the same machine involve MAMP/PHP and passing the parameters via a GET or POST to the URL. It works, but it is slow and awkward. I have found another solution. The concept is to use Applescript to put all of the parameters into a single JSON string, and put the string on the system clipboard. Then open the URL. If your server is set up with node.js with express.js framework, you can retrieve the JSON data, and pass all the parameters to the jade node template engine. With very little code, you can use the data for display, encryption, messaging, or storage in SQL. Tricks to help make this happen: Enclose the JSON elements (both the keys and the values) in tildes instead of quotes before passing to clipboard. (Also clean out all the illegal characters like newlines. I like having them at the other end, so I substitute triple-dashes for every newline and change it back on the other end.) In node.js, FIRST, replace the tildes with double quotes, and change the newline placeholders to \n. THEN use json = JSON.parse(jsonstr); to turn it from a JSON string to a JSON object. THEN use res.render(‘Jadefilename’, json); in the routes/index.js file. Inside the jade template, the jsons value can be called simply with #{key} To pass multiple jsons at once, use res.render('Jadefilename', {item1:json1, item2:json2}; etc, and inside jade the values correspond to #{item1.key} An important afterthought: these passed json objects received by jade are available in the regular jade template but INACCESSIBLE inside javascript functions nested in jade. The correction to this problem is add the following one line to the top of your nested javascript function to make the json object into a local variable: var local_json =!{JSON.stringify(imported_json)}; Now you can call the values from local_json, instead of imported_json, (item1 in the example above) inside the javascript that is nested inside the jade template. While on the subject of node.js, here is a refresher on how to get started with express. first time: install node from nodejs.org then “sudo npm install” the following: -g express generator -g nodemon mysql crypto-js copy-paste returning - check install, versions: node -v npm -v express -V (yes that one is capitalized) nodemon -v And here is what you really need to know: create an express project: express projectname-version start application with nodemon: cd projectname-version nodemon bin/www start application with debug: DEBUG=my-application ./bin/www IDE: Sublime Text 2, Terminal, Safari, Applescript Editor, Remote Desktop Connection