Accessing arguments and environment variables

Accessing arguments and environment variables

JXA scripts can access command line parameters and environment variables through NSProcessInfo properties.

Retrieving command line arguments #

As described in the introduction, you can [run JXA scripts directly from the terminal]( scripts) by adding #!/usr/bin/osascript -l JavaScript as first line to the code. With ObjC, it is very easy to get any arguments you pass on the command line:

const args = $.NSProcessInfo.processInfo.arguments;
// args[0..3] are filename, "/usr/bin/osascript", "-l", "JavaScript"
if (args.count > 4) {
  var firstArgument = args.js[4].js; // firstArgument is a string!
Take notice of the different environments here. args is an NSArray whose property count reflects the number of items. To get at a single item in JavaScript, you must convert args to a JavaScript array by calling its method js. So args.js[4] returns the fifth element of args in JavaScript. However, all elements of args are NSStrings. So you must again call js on this fifth element to obtain a JavaScript string.

Accessing environment variables #

Access to environment variables might be useful for example if you want to get the absolute path of your current working directory:

const environment = $.NSProcessInfo.processInfo.environment.js;
const currentDir = environment.PWD.js;

Here, processInfo.environment returns an NSDictionary object. It is converted to a JavaScript object by calling its js method. The PWD property of this object contains the current directory as an NSString object. To convert it to JavaScript, you have again call js.