Jump to content

A robust method to query the environment in JavaScript/JXA script filters


Recommended Posts

The currently proposed (https://www.deanishe.net/post/2018/10/workflow/environment-variables-in-alfred/#javascript-jxa) method to query an environment variable relies on the getenv function from stdlib. Unfortunately, this approach will crash the script if the variable is not set. I suggest a more robust approach:

 

ObjC.import('Foundation'); // statt ObjC.import('stdlib');
const env = $.NSProcessInfo.processInfo.environment.js; // env is a JavaScript object containing NSStrings
const envVar = (env.foo && env.foo.js) || 'default';

 

This is fine for a single variable. If you need to inquire several, use a function like so:

 

ObjC.import('Foundation'); // statt ObjC.import('stdlib');
function getenv(variableName, defaultValue) {
  const env = $.NSProcessInfo.processInfo.environment.js; // env is a JavaScript object containing NSStrings
  return (env[variableName] && env[variableName].js) ||defaultValue; // .js converts the NSString to a JavaScript one
}

const foo = getenv('foo', 'default');

This variant is robust, i.e. it does not crash the script if the environment variable is not defined.

 

As this is not a question, the post might be better suited for the "advanced workflow tips" section, but I can't post there.

 

Edited by chrillek
Link to comment
  • 9 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...